4.1 Variable in C#
Variable is a location in the memory that has name and value associated with it. The values can be integer, decimal or character. C# is type – safe language. The compiler checks the value stored in the variable is of the appropriate type. The values of the variables can be changed by the user.
The syntax to declare and initialize variables is as shown below:
<data_type><variable_name> = <value>;
In the syntax, <data_type> represents the type of data that will be stored in a variable and <value> represents the value to be stored in the variable.
The example of variable declaration is as shown below:
int age = 12;
Static variable: A field with the static modifier is called as static variable. The variable comes into existence before the static constructor is executed. The initial value of the static variable is the default value of the variable type. The example for the defining the static variable is as shown below:
public static int empno;
Instance variable: The instance variable of a class exists when a new instance of the class is created by the user. The initial value of the instance variable is the default value of the variable type. The example for defining the instance variable is as shown below:
class message
{
int msg1;
int msg2;
}
where, msg1 and msg2 are the instance variables of the class message.
Local variable: A local variable is declared by the local variable declaration which can be a block, control statements, lopping statements. The life of the local variable is the portion of the program where the execution is specified. A local variable is not initialized automatically and does not have any default value.
The rules for naming variables in C# are as follows:
1) A variable must begin with a letter or an underscore ( ‘_’ ) followed by the sequence of letters, digits, or underscores. The first character in the variable name cannot be a digit.
2) It should not contain any spaces, symbols or special character in the declaration
3) It must be unique for every variable
4) The keywords cannot be used as variable names
4.2 C# Built – in Types
The Built – in types are predefined data types that can be used directly in a program to declare variables. C# is a strongly typed language. The list of built – in types supported by C# are as follows:
Data Type | Range |
byte | 0 to 255 |
sbyte | -128 to 127 |
short | -32,768 to 32,767 |
ushort | 0 to 65,535 |
int | -2,147,483,648 to 2,147,438,647 |
uint | 0 to 4,294,967,295 |
long | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
ulong | 0 to 18,446,744,073,709,551,615 |
float | -3.402823e38 to 3.402823e38 |
double | -1.79769313486232e308 to 1.79769313486232e308 |
decimal | -79228162514264337593543950335 to 79228162514264337593542950335 |
char | A Unicode character |
string | A string of Unicode characters |
bool | True or False |
object | An object |
The C# built in types can be used in several ways as mentioned below:
Built – in types as variables:
string name = “Mark”;
int age = 40;
The data types name and int are used as variables in the above example.
Built – in types as constants:
const double pi = 3.141592653589;
const int age = 18;
Built – in types as return values and parameters
double Average1 ( int num1, int num2 )
{
double calculate;
calculate = (num1 + num2 ) / 2;
return calculate;
}
4.3 Operators in C#
Operators are used for processing variables and returning values to the user. An operator is a set of one or more characters used for the computation process. Operands are the one on which the operations are to be performed. Consider the following expression as mentioned below:
x + y
The expressions contains two operands as x and y. The operator + is used to add the values of both variables. The operators and operands used in the expression are as mentioned below:
User can use the following operators in C# programs:
1) Arithmetic operators
2) Arithmetic assignment operators
3) Unary operators
4) Comparison operators
5) Logical operators
6) Bitwise operators
1) Arithmetic operators: They are used to perform the arithmetic operations on variables. The following table shows the arithmetic operators in C#.
Operator | Description | Example |
+ | It is used to add two numbers | c=a + b; if a=10 and b=5, then c=15. |
- | It is used to subtract two numbers | c=a - b; If a=20 and b=10, then c=10. |
* | It is used to multiply two numbers | c=a * b; If a=5 and b=4, then c=20. |
/ | It is used to divide one number by another | c=a / b; If a=21 and b=2, then c=10 |
% | It is used to divide two numbers and return the reminder | C=a % b; If a=21 and b=2, then c=1 |
2) Arithmetic assignment operators: They are used to perform arithmetic operations on two given operands and assign the resultant value to any one of them. The following table shows the arithmetic assignment operators in C#.
Operator | Usage | Description |
= | x=5; | It stores the value 5 in the x variable |
+= | x+=y; | It is same as x=x + y; |
-= | x-=y; | It is same as x=x - y; |
*= | x*=y; | It is same as x=x * y; |
/= | x/=y; | It is same as x=x / y; |
%= | x%=y; | It is same as x=x % y; |
3) Unary operators: It is used to increment or decrement the value of operand by 1. The following table shows the unary operators in C#.
Operator | Usage | Description | Example |
++ | ++Operand; Or Operand++; | It is used to increment the value of operand by 1 | y= ++x; If the value of x=1, after execution both x and y have value=6.
y=x++; If the value of x=1, after execution the value of x=6 and value of y=5 |
-- | --Operand; Or Operand--; | It is used to decrement the value of the operand by 1 | y= --x; If the value of x=5, after execution both x and y have value=4
y=x--; If the value of x=5, after execution the value of x=4 and value of y=5 |
4) Comparison operators: They are used to compare the values and perform an action on the results of comparison. The expression result in the Boolean value ‘true’ and ‘false’. The following table contains the comparison operators in C#.
Operator | Usage | Description | Example |
< | expression 1 < expression 2 | It is used to check whether expression 1 is less than expression 2 | bool result; result= x < y; result will have a value true |
> | expression 1> expression 2 | It is used to check whether expression1 is greater than expression2 | bool result; result=x > y; result will have the value false |
<= | expression 1<= expression 2 | It is used to check whether expression1 is less than or equal to expression 2 | bool result; result=x <= y; result will have the value true |
>= | expression 1>= expression 2 | It is used to check whether expression 1 is greater than or equal to expression 2 | bool result; result=x>=y; result will have the value false |
== | expression 1 == expression 2 | It is used to check whether expression 1 is equal to expression 2 | bool result; result=x == y; result will have the value false |
!= | expression 1 != expression 2 | It is used to check whether expression 1 is not equal to expression 2 | bool result; result=x !=y; result will have the value true |
5) Logical operators: It is used to evaluate expressions and return a Boolean value. The following table contains the logical operators in C#.
Operator | Usage | Description | Example |
&& | expression 1 && expression 2 | It returns the value true if expression 1 and expression 2 are true | If A has value true and B has value false, then (A && B) has value false |
! | ! expression | It returns the value true if the expression is false | If A and B have value true, then !(A && B) has value false |
|| | expression 1 || expression 2 | It returns the value true if either of the expression are true | If A is true and B is false, then (A || B) has value true |
^ | expression 1 ^ expression 2 | It returns the value true if either expression is true. It returns false if any one of the expression is false | If A is true and B is false, then (A ^ B) has value false |
6) Bitwise operators: The list of Bitwise operators in C# are as mentioned below:
Operator | Description | Example |
& | It copies the bit result if it exists in both the operands | When A = 5 and B=6, then (A&B) will give 4 which is 0100 |
| | It copies the bit result if it exists in either operand | When A=5 and B=6, then (A | B) will give 7 which is 0111 |
^ | It copies the bit if it is set in one operand but not both | When A=8, B=6, then (A ^ B) will give 14 which is 1110 |
~ | It gives ones complement of the number. It is a unary operator | When A=7, then (~A) will give the value 0111 1000 |
<< | The left operands value is moved left by the number of bits specified by the right operand | When A=60 then A << 2, which will give output as 1111 0000 |
>> | The left operands value is moved right by the number of bits specified by the right operand, | When A=60 then A >>2, Which will give output as 0000 1111 |
4.4 Arrays in C#
An array is a data structure that contains a number of elements of the same type. An array is declared by defining the type of elements inside the array followed by empty brackets and a variable name. The array index starts with zero. The first element starts at the 0th position. The last position of the element will be total number of items – 1.
In C# arrays can be of two types as fixed length or dynamic. A fixed length array can store a predefined number of items. The length of the dynamic array increases when user adds new elements to it. The declaration of array in C# is as shown below:
int [ ] myArray;
The code snippet declaring that array can store 4 elements is as shown below:
int[ ] myArray;
myArray = new int [4];
Initializing Arrays: Once an array is declared, user needs to initialize the array. The initialization process means adding actual data to the array. The code snippet to add values to the array is as shown below:
//Iniitalizing a fixed array
int [ ] numArray = new int [4]{ 1, 5, 7, 11 };
//Initializing a fixed array for every element
int[ ] numArray = new int[4];
numArray[ 0 ] = 1;
numArray [ 1 ] = 5;
numArray [ 2 ] = 7;
numArray [ 3 ] = 11;
Accessing Arrays: User can access array items by passing item index in the array. The following code snippet uses the Console method to display the items.
int[ ] numArray = new int [ 4 ] ;
numArray [ 0 ] = 1;
numArray [ 1 ] = 5;
numArray [ 2 ] = 7;
numArray [ 3 ] = 11;
//Accessing one by one item from the array
Console.WriteLine( numArray[ 0 ]);
Console.WriteLine( numArray[ 1 ]);
Console.WriteLine( numArray[ 2 ]);
Console.WriteLine( numArray[ 3 ]);
Accessing array using for each loop: The for each loop is used to iterate through the items in an array. The following code snippet is used to read all the items in an array using the loop.
//Initializing and declaring dynamic array
string [ ] atr1Array = new string[ ] { “John”, “Mick”, “Joseph” };
//Read array items using foreach loop
foreach ( string str in str1Array )
{
Console.WriteLine(str);
}
Arrays in C# can be divided into three types as mentioned below:
1) Single – dimensional array
2) Multidimensional array
3) Jagged Array
1) Single-dimensional array: Single dimensional arrays are used to store number of items of a predefined type. All the items are stored in contiguous location starting from 0 to size of the array – 1.The declaration and initialization of a single – dimensional array is as mentioned below:
//array of three items of int type
int [ ] array1 = new int[3]{2,4,6};
//array of 4 items of string type
string[ ] starray1 = new string[4]{“Daisy”, “Lorel”, “Jennifer”, “Linda” };
2) Multidimensional array: Multidimensional array have more than one dimension. The multidimensional array has a matrix form. A multidimensional array can be declared as follows:
int[ , ] narray1;
A multidimensional array can be fixed or dynamic in size. The following code snippet defines multidimensional arrays with matrix of 2x2.
//Initialization of array and declaration at same time
int [ , ] num1 = new int [2, 2] { {1,3}, {2,5},{3,6}, {5,9} };
//Initializing array items one at a time
int [ , ] num1 = new int [ 2, 2];
num1 [ 0, 0 ] = 1;
num1[ 1, 0 ] = 2;
num1 [ 0, 1 ] = 4;
num1 [ 1, 1] = 8;
A multidimensional array items are represented in a matrix format. To access the elements user needs to define the matrix dimension. The following code snippet is used to define the access to members of an array.
//Access members of Multidimensional array
Console.WriteLine( num1 [ 0,0 ] );
Console.WriteLine( num1 [ 0,1 ] );
Console.WriteLine( num1 [ 1,0 ] );
Console.WriteLine( num1 [ 1,1 ] );
3) Jagged Array: Jagged Arrays are arrays of arrays. The elements of a jagged array are other arrays. While declaring jagged array, add two brackets. The following code snippet is used to initialize the jagged array.
//Initializing array and adding elements
int JaggedArray1 [ 0 ] = new int [ 2 ] ;
int JaggedArray1 [ 1 ] = new int [ 3 ] ;
User can provide values to array elements at the time of initialization. The code snippet for it is as shown below:
//Initializing array and adding values to it
int JaggedArray1 [ 0 ] = new int [ 2 ]{2,6} ;
int JaggedArray1 [ 1 ] = new int [ 3 ]{3,5,7};
User can access individual items of jagged array in the following way:
Console.WriteLine(int JaggedArray1[0][0] );
Console.WriteLine(int JaggedArray1[0][1]);