0% found this document useful (0 votes)
4 views22 pages

Chapter 2 .Net

Chapter 2 introduces the C# language, covering essential topics such as data types, operators, control structures, and method overloading. It explains various data types, type casting, boxing and unboxing, and the use of operators for arithmetic, conditional, and logical operations. Additionally, it discusses program control structures including if statements and switch cases for flow control.

Uploaded by

soceten956
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views22 pages

Chapter 2 .Net

Chapter 2 introduces the C# language, covering essential topics such as data types, operators, control structures, and method overloading. It explains various data types, type casting, boxing and unboxing, and the use of operators for arithmetic, conditional, and logical operations. Additionally, it discusses program control structures including if statements and switch cases for flow control.

Uploaded by

soceten956
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Chapter 2 Introduction to C# Language

Topics:
1. Data Types, Type Casting, Boxing and Unboxing
2. Operators
3. Conditional Structure, Looping Structure
4. Arrays, Params Parameter
5. Pass arguments by value, ref and out
6. Method overloading
7. Access Modifiers

1. List Data Types,Type Casting, Boxing and Unboxing:


1.1 Data Types
⮚ It describes what type of data a variable can hold. Variables can be declared
using data types, to tell the compiler what type of data can be stored in
variables.
⮚ It has a bulk of data types. The following table shows all the data types:
Table 2.1 DataTypes
[Link] Data Storage Value Range
Type Allocati
on

1 Depends on True or False


implementi
Boolea ng platform
n

2 Byte 1 byte 0 through 255 (unsigned)

3 Char 2 bytes 0 through 65535 (unsigned)

4 Date 8 bytes 0:00:00 (midnight) on January 1, 0001 through


11:59:59

PM on December 31, 9999

5 0 through +/-
79,228,162,514,264,337,593,543,950,335
Decima 16 bytes
l (+/-7.9...E+28) with no decimal point; 0 through
+/- 7.9228162514264337593543950335 with 28
places to

the right of the decimal

6 -1.79769313486231570E+308 through -

4.94065645841246544E-324, for negative values


Double 8 bytes 4.94065645841246544E-324 through

1.79769313486231570E+308, for positive values

7 Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed)

8 Long 8 bytes -9,223,372,036,854,775,808


through
9,223,372,036,854,775,807(si
gned)

9 4 bytes on Any type can be stored in a variable of type


32-bit Object
platform
Object

8 bytes on
64-bit
platform

10 SByte 1 byte -128 through 127 (signed)

11 Short 2 bytes -32,768 through 32,767 (signed)

12 Single 4 bytes -3.4028235E+38 through -1.401298E-45 for


negative values;

13 Depends on
implementi
String ng platform 0 to approximately 2 billion Unicode characters

14 UIntege 4 bytes 0 through 4,294,967,295 (unsigned)


r

15 ULong 8 bytes 0 through 18,446,744,073,709,551,615


(unsigned)

16 User- Depends on Each member of the structure has a range


Defined implementi determined by its data type and independent of
ng platform the ranges of the other members

17 UShort 2 bytes 0 through 65,535 (unsigned)

⮚ There are Two types of Data types:


● Value Type: It Stores variables directly. It stores the data in stack Memory.
For example Integer, Double, Single, char, short etc.
● Reference Type: It stores points to the value and refers to that value to store
the data. It stored heap memory. For example String, Object.

1.2 Type Casting:


1.2.1 Implicit conversion:
⮚ Whenever an expression involves two different types of operands, [Link]
automatically converts any intermediate values to the proper type so that the
expression can be evaluated without losing any significance.
⮚ This automatic conversion is known as implicit type conversion. When the value
of operand with lower type is assigned to the operand with higher type then
there is not any loss of accuracy, and this conversion is called widening
conversion.
⮚ The following table summarizes the widening conversions C# will perform for us
automatically.
Byte Short,Integer,Long,Decimal,Single,Double
Short Integer,Long,Decimal,Single,Double
Integer Long,Decimal,Single,Double
Long Decimal,Single,Double
Decimal Single,Double
Single Double
Double none
Char String
1.2.2 Explicit conversions:

⮚ When the value of operand with higher type is assigned to the operand with
lower type then there may be loss of accuracy and this conversion is called
narrowing conversions. When option strict is on, narrowing conversion can’t be
done.
⮚ Narrowing conversion can be done only when option strict is off. to convert its
argument to the expression is used to such as [Link],
[Link], [Link], Convert.ToInt32 (int) and
Convert.ToInt64 (long)

1.3 Boxing and Unboxing:


⮚ Boxing:
● Automatic conversion of a value type into reference type.
● Allocates the box, copies value into it.
⮚ Unboxing:
● Conversion of a reference type into value type.
● Checks the type of a box, copies the value out.
Example:
Using system:
Class test
{
Static void Main(){
Int i=123;
Object o=I; //Boxing
Int j = (int)o; //Unboxing
}
⮚ When a value of a value type is converted to type object, an object instance, also
called a "box," is allocated to hold the value, and the value is copied into that box.
Conversely, when an object reference is cast to a value type, a check is made that
the referenced object is a box of the correct value type, and, if the check succeeds,
the value in the box is copied out.

2. Operators
⮚ It is a sign which commands the compiler to perform mathematical or logical
manipulations.

2.1 Arithmetic Operator:


⮚ Following table shows all the arithmetic operators. Assume variable x holds 6 and
variable y holds 2, then:
Table 2.2 Arithmetic Operator
[Link] Operator Explanation Example

1 ^ Raises one operand to the x^y will give 36


power of another

2 + Adds two operands x +y will give 8

3 - Subtracts second operand from x - y will give 4


the first

4 * Multiplies both operands x * y will give 18

5 / Divides one operand by another


and returns a floating point
result x / y will give 2

6 MOD Modulus Operator and


remainder of after an integer
division x MOD y will give 0

2.2 Conditional Operator:

Table 2.3 Conditional Operator


[Link] Operator Explanation Example

1 > Is greater than If x>11 {

MsgBox”x is greater than 11”

2 < Is less than If x<11 {


MsgBox”x is less than 11”

3 >= Is greater than If x>=11 {


and equal to
MsgBox”x is greater or equal
to11”

4 <= Is less than If x<=11 {


and equal to
MsgBox”x is less or equal to11”

5 <> Is not If x>=11 {


equal
to MsgBox”x is not equal to11”

2.3 Logical Operators:


Table 2.4 Logical Operator
[Link]. Operator Explanation

1 ! when the condition is false it returns true


otherwise it returns false. Example:

If ! (11 =1 2) {

[Link]("(11 = 12) is False. So Not


False is True" )

2 && when the condition is true it returns true.


then after it returns False.

Example:

If (11 =11) && (22 = 22) {

[Link]("(11 = 11) is True. (22 =


22) is True. So True And True is True");

}
4 || one of the sides is true, it returns true. if the
condition is false then it returns false.

2.4 Assignment Operators:


Table 2.5 Assignment Operator
[Link] Operat Explanation Example
or

1 = Simple assignment operator, Assigns z = x + y will


values from right side operands to left assign value of
side operand x + y into z

2 += Add AND assignment operator, It adds z += x is


right operand to the left operand and equivalent to z =
assigns the result to left operand z+x

3 Subtract AND assignment operator, It z -= x is


subtracts right operand from the left equivalent to z
-= operand and assigns the result to left =z-x
operand

4 *= Multiply AND assignment operator, It Z *= x is


multiplies right operand with the left equivalent to Z
operand and assigns the result to left =Z*x
operand

5 /= Divide AND assignment operator, It Z /= x is


divides left operand with the right equivalent to Z
operand and assigns the result to left =Z/x
operand (floating point division)

6 \= Divide AND assignment operator, It Z \ = x is


divides left operand with the right equivalent to Z
operand and assigns the result to left =Z\x
operand (Integer division)

7 ^= Exponentiation and assignment operator. Z^=x is equivalent


It raises the left operand to the power of to Z = Z^ x
the right operand and assigns the result
to left operand

3. Program Control Structure:


⮚ Statements in a program are executed one after another in the order in which
they are written.
3.1 Conditional Structure:
o If statement
o Select case statement
3.1.1 If/Then Selection Structure
⮚ In this statement it checks a condition if it is true then the statement is executed
otherwise it is ignored.
Syntax:

If (condition)
{
//statements
}

Example 1:
Using System;
class ifstatement
{
public static void Main()
{
int a, b;
[Link]("Enter the value of a:” ) ;
a = [Link]([Link]());
[Link]("Enter the value of b: ");
b = [Link]([Link]());

If (a>b)
{
[Link](“a is greater
than b”);
}
[Link]();
}
}
3.1.2 If/Then/Else Selection Structure
⮚ The If/ Then statement shows that the code of the if block executed whether the
condition is true otherwise the else block of code is executed. the conditional
operators are used with the particular condition.
Syntax:
If (condition)
{
\\Statements
}
Else
{
\\Statements
}
Example 1:
Using System;
class ifstatement
{
public static void Main()
{
int a, b;
[Link]("Enter the value of a:” ) ;
a = [Link]([Link]());
[Link]("Enter the value of b: ");
b = [Link]([Link]());

If (a>b)
{
[Link](“a is greater than b”);
}
Else
{
[Link](“b is greater than a”);
}
[Link]();

}
}

3.1.3 Nested If/ then..Else statement:

⮚ Nested If..Then..Else statement is used to test more than one condition. it is inside
one another in the if then else statement.
Syntax:
If (Condition)
{
If (Condition)
{
[Statements]
}
Else
{
[Statements]
}
Else
{
[Statements]
}
Example 1. :
Using System;
class ifstatement
{
public static void Main()
{
int a, b,c;
[Link]("Enter the value of a:” ) ;
a = [Link]([Link]());
[Link]("Enter the value of b: ");
b = [Link]([Link]());
[Link]("Enter the value of c: ");
c = [Link]([Link]());

If (a>b)
{
If (a>c)
{
[Link](“a is greater”);
Else
{
[Link](“c is greater”);
}
}
Else
{
If (b>c)
{
[Link](“b is greater”);
}
Else
{
[Link](“c is greater”);
}
}
}
3.1.4 Else- If Ladder:
⮚ The condition is used with the else if ladder and test multiple conditions. if the
condition is true then if part is executed and false then elseif condition tested in
order and continue to check conditions. the statement is ending with the End If
keyword.
Syntax:

If (condition1)
{
‘Statements1
}
ElseIf (condition2)
{
‘Statement2
}
ElseIf (condition3)
{
‘Statement3
}


ElseIf (Condition N)
{
‘Statement N
}
Else
{
‘Statement Else
}
Example:
Using System;
class ifstatement
{
public static void Main()
{
int a, b,c;
[Link]("Enter the value of a:” ) ;
a = [Link]([Link]());
[Link]("Enter the value of b: ");
b = [Link]([Link]());
[Link]("Enter the value of c: ");
c = [Link]([Link]());
if(a>b)
{
[Link]("a is greater");
}
else If(a< b)
{
[Link]("b is greater");
}
else
{
[Link]("both are Equals");
}
[Link]();
}

3.2 Switch Statement


⮚ Switch is a selection statement. It matches the value and executes the particular
case argument at a runtime.
Syntax:
Switch(<Expression>)
{
Case <Value> :
\\statements
Break;
-----------------------
-------------------------
------------------------
Default :
\\statements
Break;
}
Flow Diagram:

Figure 2.1 Flow chart of select case statement

Example
Class switch
{
public static void Main()
{
int a, b, choice;

[Link]("Enter the value of a:” ) ;


a = [Link]([Link]());
[Link]("Enter the value of b: ");
b = [Link]([Link]());

[Link]( "1: addition" );


[Link]( "1: subtraction" );
[Link]( "1: multiplication" );
[Link]( "1: division" );
[Link]( "enter value of choice" );
choice = [Link]([Link]());

Switch (choice)
{
Case 1 :
[Link]( "addition is" & a + b);
break;
Case 2 :
[Link]( "subtraction is" & a - b);
break;

Case 3 :
[Link]( "multiplication is" & a * b);
break;

Case 4 :
[Link]( "division is" & a / b);
break;
}
[Link]();
}

3.3 Loop structure


● For Loop
● While loop
● Do ... While Loop
● Foreach Loop
⮚ Each and every loop requires the following 3 things in common.
1. Initialization: that sets a starting point of the loop
2. Condition: that sets an ending point of the loop
3. Iteration: that provides each level, either in the forward or backward direction
3.3.1 Do...Loop While loop
A Do...Loop While loop executes until the loop's condition becomes false. after
each iteration of the loop, Its condition is checked.
Syntax:

Do
{
//statement
}
While(Condition)

3.3.2 For loop


⮚ A For loop iterates a number of times.
Syntax:
For(initializr; Condition; iterator)
{
//statement
}
Example:
Class forexp
{
public static void Main()
{
int i;
for(i=0; i<5; i++)
{
[Link](i);
}
}
}
Output:
0
1
2
3
4
3.3.3 While-loops
⮚ While-loops run when the condition is true. To avoid the infinite loops while loop is
useful and it is used to execute a number of iterations.
Syntax:
While(Condition)
{
// statement
}

Example:
Class forexp
{
public static void Main()
{
int i=0;
While (i < 100)
{
[Link](i);
i += 10
}
}
}
Output:
0
10
20
30
40
50
60
70
80
90

3.4 For Each Loop:


⮚ The foreach loop is used to loop over elements in an array:
Syntax:
foreach (type variableName in arrayName)
{
// code block to be executed
}
Example:
using System;

namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
[Link](i);
}
}
}
}
Output:

4 Arrays:
⮚ An array is the fixed -size sequential collection of elements which stores the
same type of array . An array is used to store a collection of data. Arrays start
from zero. So the first number of array is array name(0)
⮚ To declare an array datatype[] arrayName;

4.1 Multi-Dimensional Arrays:


⮚ Multidimensional arrays are also called rectangular arrays. Declare a 2-
dimensional array of Integer as:
int [,] a = new int [3,4] {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

Example:
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
/* an array with 5 rows and 2 columns*/
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
int i, j;

/* output each array element's value */


for (i = 0; i < 5; i++) {

for (j = 0; j < 2; j++) {


[Link]("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}
[Link]();
}
}
}

Output:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

4.2 Jagged array:


⮚ A jagged array is an array within an array. Each entry i n the array is another
array that can hold any number of items. It is an array of arrays with
parentheses in multiple sets. The first parenthesis indicate the size of the
jagged array. Declare a jagged array through the use of a couple of units.
⮚ '"jagged" array: array of (array of
nteger)
int [ ][ ] jagged_array;
int[ ][ ] jagged_array = new int[2][]{new int[ ]{92,93,94},new int[ ]{85,66,87,88}};

Example:
using System;
class MyArray {
static void Main(string[] args) {

int [ ][ ] jagged = New int[ ] [ ] {


jagged[0] = New Int [ ] {1}
jagged[1] = New Integer[ ]{3, 4}
jagged[2] = New Integer [ ] {5, 6, 7}
jagged[3] = New Integer[ ] {5, 6}
jagged[4] = New Integer[ ] {9}
}
int i,j;
For (i = 0; i<[Link](0); i++)
{
For (j=0; j<jagged(i).GetUpperBound(0); j++)
{
[Link](jagged(i)(j) & " ");
}
}

}
}
Output:
1
34
567
56
9

4.3 Parameter Array:


1. Methods can have a variable number of arguments ,called a parameter array.
2. Params keyword declares parameter array.
3. Must be the last argument.
Example:
using system;
class hello
{
public static void main ()
{
hello h=new hello();
[Link]();
}
void pqr()
{
abc(2,”abc”,”pqr”,”xyz”);
abc(20,”hi”);
abc(2);
}
void abc(int I,params string[] b)
{
foreach(string s in b)
{
[Link](s+”.”+i);
}
}
}
5. Method Overloading
⮚ Method overloading permits multiple methods in the same class to have the
same name as long as they have unique signatures.
⮚ When compiling an invocation of an overloaded method, the compiler uses
overload resolution to determine the specific method to invoke. Overload
resolution finds the one method that best matches the arguments or reports an
error if no single best match can be found.
⮚ The following example shows overload resolution in effect. The comment for
each invocation in the Main method shows which method is actually invoked.
Class test
{
Static void F()
{
[Link](“F()”);
}
Static void F(object x)
{
[Link](“F(object)”);
}
Static void F(int x)
{
[Link](“F(int)”);
}
Static void F(double x)
{
[Link](“F(double)”);
}
Static void F(double x, double y) {
[Link](“F(double,double)”);
}
static void main()
{
F(); //Invokes f()
F(1); //Invokes f(int)
F(1,0); //Invokes f(double)
F(“abc”); //Invokes f(object)
F((double)1); //Invokes f(double)
F((object)1); //Invokes f(object)
F(1,1); //Invokes f(double,double)
}
}

6. Pass argument by value

6.1 Pass argument by value


⮚ In c#Passing a Value-Type parameter to a method by value means passing a
copy of the variable to the method. So the changes made to the parameter
inside the called method will not affect the original data stored in the argument
variable.
Example:
sing System;

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 10;
[Link]("Variable Value Before Calling the Method: {0}", x);
Multiplication(x);
[Link]("Variable Value After Calling the Method: {0}", x);
[Link]("Press Enter Key to Exit..");
[Link]();
}
public static void Multiplication(int a)
{
a *= a;
[Link]("Variable Value Inside the Method: {0}", a);
}
}
}
Output :

6.2 Ref and Out


6.2.1 REF Keyword
⮚ The ref modifier causes arguments to be passed by reference
· Allows a method call to modify a variable
· Have to use ref modifier in method definition and the code that calls it A
Variable has to have a value before call.
Example:
Class program
{
Static void main()
{
Int n=5;
Yy(ref n);
[Link](“{0}”,n);
}
X=10;
[Link](“{0}”.x);
}
}

Output:
10
10
⮚ In this example, it is not the value of n that is passed, rather a reference to n is
The parameter x is not an int. it is a reference to n.
⮚ Therefore, when x is equal to 10 inside the method, what actually gets x refers
to n.
⮚ The value of the parameter is changed after calling the method.

6.2.2 OUT keyword

⮚ Using the 'out' keyword you can only write.


⮚ i.e. you can only change the value of the variable, you can not read it. So, in ca
since it does not read the variable, it doesn't matter even if it is not initialized.
class zzz
{
Public static void main()
{
yyy a;
int i=100;
a-new yyy();
[Link](out i);
[Link]("1");
}
}
Class yyy
{
public void abc(out int i)
{
I=10;
}
}

Output:
10

⮚ In this program, we now have 'out' in both cases:


⮚ In the function call and the function itself. So, by saying [Link] (out i) you are
implying that you are allowing the function abc to change the value of i. so, it
knows i going to change & hence I know changes in the original. That's why
write will display the new value 10.
7. Access Modifiers
⮚ Access modifiers are keywords used to specify the declared accessibility of a
member or a type.
1. It allows us to define who does and doesn’t have access to certain
features.
2. In C# There are 5 different types of access modifiers.
Table: 2.6 Modifier
Modifier Description

Public There are no restrictions on accessing public members.

Protected Access is limited to within the class definition and any class that
inherits from the class.

Access is limited to within the class definition. This is the default


access modifier type if none is formally specified.
Private

Internal Access is limited exclusively to classes defined within the current


project assembly.

Protected Access is limited to the current assembly and types derived from the
containing class. All members in the current project and all members
Internal in derived class can access the variables.

⮚ Public:
There are no restrictions on accessing public members.
Accessibility:
Can be accessed by objects of the class.
Can be accessed by derived class.
Example:
Class AccessMod
{
Public int num1;
}
Class program
{
Static void main()
{
AccessMod ob1=new AccessMod();
ob1.num1=100;
[Link](“Number is {0}”,ob1.num1);
[Link]();
}
}
Output:
Number is 100

⮚ Private:
Private members are accessible only within the body of the class or the struct in
which they are declared.
Accessibility:
● Connect can be accessed by object.
● Connect can be accessed by derived classes.

Example:
class AccessMod
{
public int num1;
int num2;
}
class program
{ static void main()
{ AccessMod ob1=new AccessMod();
Ob1.num1=100;
Ob1.num2=20; //Access to private members is not permitted.
}
}
Output:
Error: Compile error

⮚ Protected:
A protected member is accessible from within the class in which it is declared,
and from within any class derived from the class that declared this member.
Accessibility:
● Cannot be accessed by object.
● By derived class.
Example:
Previous examples like Inheritance.

⮚ Internal:
We can declare a class as internal or its members as internal. Internal
members are accessible only within files in the same assembly (.dll).
Accessibility:
In same assembly (public):
● Can be accessed by objects of the class.
● Can be accessed by derived class.
In other assembly:
● Cannot be accessed by object.
● Cannot be accessed by derived class.
⮚ Protected internal:
● The protected internal accessibility means protected or internal, not
protected and internal.
● A protected internal member is accessible from any class in the same
assembly, including derived class.
● Inherited types, they belong to a different assembly, have access to the
protected internal members.
● Types that reside in the same assembly, even if they are not derived from
the type, also have access to the protected internal members.

You might also like