C#dotnet Unit-2 LM
C#dotnet Unit-2 LM
Objective:
To impart the concepts of control structures, classes, objects in .NET
Syllabus:
UNIT - II: Control Statements
Introduction to data types: Value Type - Primitive types, Arrays, Reference
Type, Keywords, variables, Operators and Literals in C#
Type Casting- Primitive type casting, Boxing and Unboxing, Special Operators
in C#
Conditional Statements- if, if-else, if-else-if ladder, nested if, switch
statements with examples
Iterative Statements- while, do-while, for, foreach, break, continue
statements with examples
Outcomes:
Students will be able to
Understand various data types in C#
Understand various conditional and iterative control structures
Compose simple programs in C# using control structures
Learning Material
Introduction to data types: Value Type - Primitive types, Arrays, Reference
Type:
Data type:
A data type is defined as a categorizing one of various types of data, such
as floating point and integer, and the operations that can done on that
type.
Data types are especially important in C# because it is a strongly typed
language. This means that, all operations are type-checked by the
compiler for type compatibility. Illegal operations will not be compiled.
Thus, strong type-checking helpsto prevent errors and enhances
reliability.
To enable strong type-checking, all variables,expressions, and values
have a type (data type).
C# contains two general categories of built-in data types: value types and
reference types. The difference between the two types is what a variable
contains. For a value type, a variable holds an actual value, such 3.1416
or
212. For a reference type, a variable holds a reference to the value.
213.
Value type:
Value type variables can be assigned a value directly. Value of value type
to a variable or field or array element of value type makes a copy of the
value.They are derived from the class System.ValueType.To get the exact size
of a type or a variable use the sizeof() method. The expression sizeof(type)
yields the storage size of the object or type in bytes.
Primitive types:
A value type is a simple type, a struct type or an enum type.Assigning a
Some of the primitive (fundamental) data types:
Reference type:
The reference data types do not contain the actual data stored in a
variable, but they contain a reference to the variables.
If the data is changed by one of the variables, the other variable
automatically reflects this change in value.
A reference type is a class, an interface, an array type, or a delegate
type.
Arrays: Array in C# is a group of similar types of elements that have
contiguous memory location. In C#, array is an object of base type
System.Array. In C#, array index starts from 0. We can store only fixed set of
elements in C# array.
There are 2 methods commonly used for declaring arrays. While both have
their place and usage, most programmers prefer the dynamic array that is
declared at run-time to provide the most flexibility.
The static array is great if you have a set structure that will never change.
An array that holds the days of the week, months in the year, or even the
colors in a rainbow are the static arrays. These won't change and they won't
be data driven so in this case, a static array will be best.
C# Array Properties:
Property Description
IsFixedSize It is used to get a value indicating whether the Array has a fixed
size or not.
IsReadOnly It is used to check that the Array is read-only or not.
Length It is used to get the total number of elements in all the
dimensions of the Array.
LongLength It is used to get a 64-bit integer that represents the total number
of elements in all the dimensions of the Array.
Rank It is used to get the rank (number of dimensions) of the Array.
C# Array Methods:
Method Description
Clear(Array,Int32,Int32) It is used to set a range of elements in an array to
the default value.
Clone() It is used to create a shallow copy of the Array.
Copy(Array,Array,Int32) It is used to copy elements of an array into
another array by specifying starting index.
Empty<T>() It is used to return an empty array.
Finalize() It is used to free resources and perform cleanup operations.
IndexOf(Array,Object) It is used to search for the specified object and returns
the index of its first occurrence in a one-dimensional array.
Initialize() It is used to initialize every element of the value-type Array by
calling the default constructor of the value type.
Reverse(Array) It is used to reverse the sequence of the elements in the
entire one-dimensional Array.
Sort(Array) It is used to sort the elements in an entire one-dimensional
Array.
ToString() It is used to return a string that represents the current object.
//Example program on Array properties and methods
using System;
namespaceCSharpProgram
{ class Program {
static void Main(string[] args) {
// Creating an array
int[] arr = new int[6] { 5, 8, 9, 25, 0, 7 };
// Creating an empty array
int[] arr2 = new int[6];
// Displaying length of array
Console.WriteLine("length of first array: "+arr.Length);
// Sorting array
Array.Sort(arr);
Console.Write("First array elements: ");
// Displaying sorted array
PrintArray(arr);
// Finding index of an array element
Console.WriteLine("\nIndex position of 25 is "+Array.IndexOf(arr,25));
// Coping first array to empty array
Array.Copy(arr, arr2, arr.Length);
Console.Write("Second array elements: ");
// Displaying second array
PrintArray(arr2);
Array.Reverse(arr);
Console.Write("\nFirst Array elements in reverse order: ");
PrintArray(arr);
}
// User defined method for iterating array elements
static void PrintArray(int[] arr)
{
foreach (Object elem in arr)
{
Console.Write(elem+" ");
}
}
}
}
Single Dimensional Array
To create single dimensional array, you need to use square brackets []
after the type.
int[] arr = new int[3]{10,20,30};//creating Static array
int[] arr = { 10, 20, 30, 40, 50 }; creating Dynamic array
int[] arr = new int[]{10,20,30}; //creating Dynamic array
Let's see a simple example of C# array, where we are going to declare,
initialize and traverse array.
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = new int[5];//creating dynamic array
arr[0] = 10;//initializing array
arr[2] = 20;
arr[4] = 30;
//traversing array
for (int i = 0; i <arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
}
Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C#. It
can be two dimensional or three dimensional. The data is stored in tabular
form (row * column) which is also known as matrix.
To create multidimensional array, we need to use comma inside the
square brackets. For example:
int[,] arr=new int[3,3];//declaration of 2D array
int[,,] arr=new int[3,3,3];//declaration of 3D array
There are 3 ways to initialize multidimensional array in C# while declaration.
1. int[,] arr = new int[3,3]= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//Static
2. We can omit the array size.
int[,] arr = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//Dynamic array
We can omit the new operator also.
3. int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; //Dynamic array
Let's see a simple example of multidimensional array in C# which
declares, initializes and traverse two dimensional array.
Ex:using System;
public class MultiArrayExample
{
public static void Main(string[] args)
{
int[,] arr=new int[3,3];//declaration of 2D static array
arr[0,1]=10;//initialization
arr[1,2]=20;
arr[2,0]=30;
//traversal
for(int
i=0;i<3;i++){ for(int
j=0;j<3;j++){
Console.Write(arr[i,j]+" ");
}
Console.WriteLine();//new line at each row
}
}
}
Jagged Arrays
In C#, jagged arrayis also known as "array of arrays" because its
elements are arrays. The element size of jagged array can be different.
Declaration of Jagged array
Let's see an example to declare jagged array that has two elements.
int[][] arr = new int[2][];
Initialization of Jagged array
Let's see an example to initialize jagged array. The size of elements can be
different.
arr[0] = new int[4];
arr[1] = new int[6];
Initialization and filling elements in Jagged array
Let's see an example to initialize and fill elements in jagged array (Static).
arr[0] = new int[4] { 11, 21, 56, 78 };
arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };
Here, size of elements in jagged array is optional. So, you can write above
code as given below:
arr[0] = new int[] { 11, 21, 56, 78 };
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
Let's see an example to initialize the jagged array while declaration.
int[][] arr = new int[3][]
{
new int[] { 11, 21, 56, 78 },
new int[] { 2, 5, 6, 7, 98, 5 },
new int[] { 2, 5 }
};
Let's see a simple example of jagged array in C# which declares, initializes, and
traverse jagged arrays.
public class JaggedArrayTest
{
public static void Main()
{
int[][] arr = new int[2][];// Declare the Jagged array
arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
// Traverse array elements
for (int i = 0; i <arr.Length; i++)
{
for (int j = 0; j <arr[i].Length; j++)
{
System.Console.Write(arr[i][j]+" ");
}
System.Console.WriteLine();
}
} }
Keywords, variables, Operators and Literals in C#:
Keywords:
A computer language is defined by its keywords because they determine
the features built into the language.
C# defines two general types of keywords: reserved and contextual.
Keywords are predefined, reserved identifiers that have special meanings
to the compiler.
They cannot be used as identifiers in your program unless they include
@ as a prefix.
For example, @if is a valid identifier, but if is not because if is a keyword.
Variables:
A variable is a name given to a storage area that our programs can
manipulate.
Each variable in C# has a specific type.
A variable is declared inside a method body, constructor body, or another
block statement.
The variable can be used only in that block statement, and only after it
has been declared.
C# Naming conventions of a variable:
May contain letters (a-z/A-Z), decimal digits (0-9), _ (underscore).
Can start with a capital letter before the keyword
Can use @ at beginning of any keyword
It should not be a keyword
White spaces ar not allowed
Variable names can be of any length
Variable names are case sensitive; Sum and sum are different names
Defining Variables:
Syntax for variable definition in C# is
<data_type><variable_list>;
Example: int i, j, k;int @int;
Initializing Variables:
Variables are initialized (assigned a value) with an equal sign followed by a
constant expression. The general form of initialization is
variable_name = value; or <data_type><variable_name> = value;
Example: i=10, j=20; orint d = 3, f = 5;
Operators:
C# provides an extensive set of operators that give the programmer
detailed controlover the construction and evaluation of expressions. Most of
C#’s operators fall intothe following categories: arithmetic, bitwise, relational,
and logical.
Arithmetic operators:
// C# program to demonstrate the
working of Arithmetic Operators
using System;
namespace Arithmetic {
classsample {
static void Main(string[] args)
{ int result;
int x = 10, y = 5;
result = (x + y);
Console.WriteLine("Addition Operator: {0}", result);
result = (x - y);
Console.WriteLine("Subtraction Operator: {0}",result);
result = (x * y);
Console.WriteLine("Multiplication Operator: {0}",result);
result = (x / y);
Console.WriteLine("Division Operator: {0}",result);
result = (x % y);
Console.WriteLine("Modulo Operator: {0}",result);
}
}}
Bitwise operators: (AND, OR, XOR, and NOT)
C# provides a set of bitwise operators that expand the types of problems
to which C# can beapplied.
The bitwise operators act directly upon the bits of their operands.
They are definedonly for integer operands.
They cannot be used on bool, float, or double.
They are called the bitwise operators because they are used to test, set,
or shift the bitsthat comprise an integer value.
The bitwise operators AND, OR, XOR, and NOT are &, |, ^, and ~.
using System;
namespace Operator{
classRelationalOperator{
public static void Main(string[]
args){ bool result;
int f = 10, s = 20;
result = (f==s);
Console.WriteLine("{0} == {1} returns {2}",f, s, result);
result = (f>s);
Console.WriteLine("{0} > {1} returns {2}",f, s, result);
result = (f< s);
Console.WriteLine("{0} < {1} returns {2}",f, s, result);
result = (f>= s);
Console.WriteLine("{0} >= {1} returns {2}",f, s, result);
result = (f <= s);
Console.WriteLine("{0} <= {1} returns {2}",f, s, result);
result = (f != s);
Console.WriteLine("{0} != {1} returns {2}",f, s, result);
}
}}
Output: 10 == 20 returns False
10 > 20 returns False
10 < 20 returns True
10 >= 20 returns False
10 <= 20 returns True
10 != 20 returns True
Logical operators are used to perform logical operation such as AND, OR,
and NOT. Logical operators on boolean expressions (true and false) and returns
Boolean values. Logical operators are used in decision making and loops.
Logical AND: The ‘&&’ operator returns true when both the conditions in
consideration are satisfied. Otherwise it returns false.
Logical OR: The ‘||’ operator returns true when one (or both) of the
conditions in consideration is satisfied. Otherwise it returns false
Logical NOT: The ‘!’ operator returns true the condition in consideration
is not satisfied. Otherwise it returns false.
// C# program to demonstrate the working
// of Logical Operators
using System;
namespace Logical
{ classlogicalsample{
static void Main(string[] args) {
bool a = true,b = false, result;
result = a && b;
Console.WriteLine("AND Operator: {0}",result);
result = a || b;
Console.WriteLine("OR Operator: {0}",result);
result = !a;
Console.WriteLine("NOT Operator: {0}",result);
}
}}
Literals:
Literals are value constants that are
assigned to variables in a program. C#
supports several types of literals.
Integer literals: An integer literal refers to the sequence of digits. An
integer literal can be a decimal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal.
Ex: 85 /* decimal */
0x4b /* hexadecimal */
Real/Floating literals:A floating-point literal has an integer part, a
decimal point, a fractional part, and an exponent part. We can represent
floating point literals either in decimal form or exponential form.
Mantissa e/E exponent
Ex: 7500 can be7.5E3//7.5x103
Character literals are enclosed in single quotes. For example, 'x' and can
be stored in a simple variable of char type. A character literal can be a
plain character (such as 'x'), an escape sequence (such as '\t').
Ex: char ch = 'a';
String literals are enclosed in double quotes "" or with @"". A string
contains characters that are similar to character literals: plain characters,
escape sequences, and universal characters.
Ex: string s1=”welcome”; string s2= @”welcome”;
Type Casting- Primitive type casting:
Type casting refers to the conversion of a data type into another data
type. This is done in two ways 1. Implicit 2. Explicit
Implicit conversion can be done by the system automatically.
Explicit conversion is achieved manually by specifying the target data
type in the parenthesis before operandon the right side of an assignment
operator.
There are many primitive types in C# that are converted implicitly by the
rule, i.e. the target type must be larger than the source type.
The following list shows the type conversions between .NET types.
From To
sbyte (Signed 8-bit integer) short, int, long, float, double, or decimal
byte (unsigned 8-bit integer) short, ushort, int, uint, long, ulong,
float, double, or decimal
char ushort, int, uint, long, ulong, float,
double, or decimal
short (Signed 16-bit integer) int, long, float, double, or decimal
ushort(unsigned 16-bit integer) int, uint, long, ulong, float, double, or
decimal
int (Signed 32-bit integer) long, float, double, or decimal
uint (unsigned 32-bit integer) long, ulong, float, double, or decimal
long (Signed 64-bit integer) float, double, or decimal
ulong (unsigned 64-bit integer) float, double, or decimal
float double
Ex: using System;
namespace
ConsoleApplication1{ class
Program {
static public void Main(string[]
args){ int x = 10;
double d = x; //implicit conversion
float f= (float)x; // Explicit conversion
Console.WriteLine(d);
Console.ReadKey();
}
}
}