BOXING AND UNBOXING TYPES
Boxing refers to converting a value type to an object type, and unboxing refers to the opposite.
Boxing is carried out implicitly in C#, use type casting to unbox to an appropriate data type.
For example
int i; Console.WriteLine("i={0}",i);
The WriteLine() method requires an object, so in the above statement integer i is implicitly boxed to an object and passed to the WriteLine method.
An example for unboxing is
int i;
object obj = i; // boxing is implicit
int j;
j = (int) obj; // to unbox we use type cast
Typically unboxing is done in a try block. If the object being unboxed is null or if the unboxing cannot succeed because the object is of a different type, an InvalidCastException is thrown.
DELEGATES
A delegate essentially creates a name for a the specific type/signature of a method. Delegates are type safe function pointers.
One must first declare a delegate.
// delegates.cs
using System;
// declare delegate with the signature of the encapsulated method
delegate void MyDelegate(string m,int a,int b);
class Application
{
public static void Main()
{
MyDelegate md = new MyDelegate(FirstMethod);
md += new MyDelegate(SecondMethod);
md("message A",4,5);
md("message B",7,11);
} // end Main
}
static void FirstMethod(string s1,int x1,int y1)
{
Console.WriteLine("1st method: " + s1);
int sum1 = x1 + y1;
Console.WriteLine("sum1 = " + sum1);
}
static void SecondMethod(string s2,int x2,int y2)
{
Console.WriteLine("2st method: " + s2);
int sum2 = x2 + y2;
Console.WriteLine("sum2 = " + sum2);
}
OUTPUT :
1st method message A
sum1 = 9
2st method message A
sum2 = 9
1st method message B
sum1 = 18
2st method message B
sum2 = 18
TYPES :
The typeof command is an operator. It resolves at compile time and operates over a type. To check whether an object is compatible to a specific type is to apply the is keyword.
// myTypeof.cs
using System;
using System.Text;
class myTypeof
{
public static void Main()
{
double b = 3.14;
string s = "xxx";
StringBuilder sb = new StringBuilder("123456789");
}
Type at = typeof(double);
Console.WriteLine("at = {0}",at);
Type st = typeof(string);
Console.WriteLine("st = {0}",st);
Type sbt = typeof(StringBuilder);
Console.WriteLine("sbt = {0}",sbt);
if(s is string)
{
Console.WriteLine(at);
}
if(s is StringBuilder)
{
Console.Write("s is of the StringBuilder");
}
else
{
Console.Write("s is not of StringBuilder");
}
if(b is int)
{
Console.WriteLine("b is int");
}
}
Thursday, May 13, 2010
Arrays
Arrays in C#
Array Declaration :
An Array is a collection of values of a similar data type. Technically, C# arrays are a reference type. Each array in C# is an object and is inherited from the System.Array class. Arrays are declared as:
[]
Let's define an array of type int to hold 10 integers.
int [] integers = new int[10];
The size of an array is fixed and must be defined before using it. However, you can use variables to define the size of the array:
int size = 10;
int [] integers = new int[size];
You can optionally do declaration and initialization in separate steps:
int [] integers;
integers = new int[10]
It is also possible to define arrays using the values it will hold by enclosing values in curly brackets and separating individual values with a comma:
int [] integers = {1, 2, 3, 4, 5}
This will create an array of size 5, whose successive values will be 1, 2, 3, 4 and 5.
Accessing the values stored in an array
To access the values in an Array, we use the indexing operator [int index]. We do this by passing an int to indicate which particular index value we wish to access. It's important to note that index values in C# start from 0. So if an array contains 5 elements, the first element would be at index 0, the second at index 1 and the last (fifth) at index 4. The following lines demonstrate how to access the 3rd element of an array:
int [] intArray = {5, 10, 15, 20};
int j = intArray[2];
PROGRAM :
// demonstrates the use of arrays in C#
static void Main()
{
// declaring and initializing an array of type integer
int [] integers = {3, 7, 2, 14, 65};
// iterating through the array and printing each element
for(int i=0; i<5; i++)
{
Console.WriteLine(integers[i]);
}
}
Here we used the for loop to iterate through the array and the Console.WriteLine() method to print each individual element of the array. Note how the indexing operator [] is used.
The above program is quite simple and efficient, but we had to hard-code the size of the array in the for loop. As we mentioned earlier, arrays in C# are reference type and are a sub-class of the System.Array Class. This class has lot of useful properties and methods that can be applied to any instance of an array that we define. Properties are very much like the combination of getter and setter methods in common Object Oriented languages.
Properties are context sensitive, which means that the compiler can un-ambiguously identify whether it should call the getter or setter in any given context. We will discuss properties in detail in the coming lessons. System.Array has a very useful read-only property named Length that can be used to find the length, or size, of an array programatically.
Using the Length property, the for loop in the above program can be written as:
for(int i=0; i
{
Console.WriteLine(integers[i]);
}
This version of looping is much more flexible and can be applied to an array of any size and of any data-type. Now we can understand the usual description of Main(). Main is usually declared as:
static void Main(string [] args)
The command line arguments that we pass when executing our program are available in our programs through an array of type string identified by the args string array.
int[] numbers = new int[20];
Array Initialization :
int[] numbers = {0, 1, 2, 3, 5};
This is identical to the complete initialisation statement:
int[] numbers = new int[] {0, 1, 2, 3, 5};
array types. The class Array contains methods for sorting and searching.
using System;
class myArray
public static void Main()
Console.Write("\n");
int pos1 = Array.BinarySearch(slist,"carl");
Array.Sort(slist);
Console.Write("pos2 = {0}",pos2); Console.WriteLine();
for(int j=0;j
public class TwoDim
public static void Main()
double[,] myarray;
Flow Of Control and Conditional Statements
Introduction
A program based purely on sequential execution will, during each execution, always perform exactly the same actions; it is unable to react in response to current conditions.
The flow of control is the order in which statements of a program are executed.Other terms used are ordering and control flow.Group of statements used for the exact purpose , collectively called branching statements.A branch is a segment of a program made up of one statement or a group of statements.
A branching statement chooses to execute just one of several statements or blocks of statements .The choice made depends on a given condition.Branching statements are also called selection statements or alteration statements.
An iteration statement repeats a statement or a block of statements until a given termination condition is met.Iteration statements are also referred to as loop statements or repetition statements.
Branching With The IF Statement
The value of relational operators is that they can be used to make decisions to change the flow of the execution of your program. The if keyword can be used with the relational operators to change the program flow.
The if-else keyword is used to compare two values. The standard format of the if command is as follows:
if( val1 [operator] val2) statement(s) else statement(s);
operator is one of the relational operators; val1 and val2 are variables, constants, or liter- als; and statement(s) is a single statement or a block containing multiple statements. Remember that a block is one or more statements between brackets.
If the comparison of val1 to val2 is true, the statements are executed. If the comparison of val1 to val2 is false, the statements in the fast loop are executed.
EXAMPLE :
// ifelsetest.cs- The if statement
//----------------------------------------------------
class ifelsetest
{
public static void Main()
{
int Val1 = 1;
int Val2 = 0;
System.Console.WriteLine(“Getting ready to do the if...”);
if (Val1 == Val2)
{
System.Console.WriteLine(“If condition was true”);
}
else
{
System.Console.WriteLine("If condition was false");
}
System.Console.WriteLine(“Done with the if statement”);
}
}
OUTPUT :
Getting ready to do the if...
Done with the if statement
THE SWITCH STATEMENT :
C# provides a much easier way to modify program flow based on multiple values stored
in a variable: the switch statement. The format of the switch statement is as follows:
switch ( value )
{
case result_1 :
// do stuff for result_1
break;
case result_2 :
// do stuff for result_2
break;
... case result_n :
// do stuff for result_x
break;
default:
// do stuff for default case
break;
}
The value in the switch statement can be the result of an expression, or it can be a variable. This value is then compared to each of the values in each of the case statements until a match is found. If a match is not found, the flow goes to the default case. If there is not a default case, flow goes to the first statement following the switch statement.
When a match is found, the code within the matching case statement is executed. When the flow reaches another case statement, the switch statement ends. Only one case statement is executed at most. Flow then continues, with the first command following the switch statement.
Example :
// roll.cs- Using the switch statement.
//--------------------------------------------------------------------
class roll
{
public static void Main()
{
int roll = 0;
// The next two lines set the roll to a random number from 1 to 6
System.Random rnd = new System.Random();
roll = (int) rnd.Next(1,7);
System.Console.WriteLine(“Starting the switch... “);
switch (roll)
{
case 1:
System.Console.WriteLine(“Roll is 1”);
break;
case 2:
System.Console.WriteLine(“Roll is 2”);
break;
case 3:
System.Console.WriteLine(“Roll is 3”);
break;
case 4:
System.Console.WriteLine(“Roll is 4”);
break;
case 5:
System.Console.WriteLine(“Roll is 5”);
break;
case 6:
System.Console.WriteLine(“Roll is 6”);
break;
default:
System.Console.WriteLine(“Roll is not 1 through 6”);
break;
}
System.Console.WriteLine(“The switch statement is now over!”);
}
}
OUTPUT :
Starting the switch...
Roll is 1
The switch statement is now over!
NOTE : Your answer for the roll in the output might be a number other than 1.
EXECUTING MORE THAN ONE CASE STATEMENT :
To do this in C#, goto command is used. The goto command can be used within the switch statement to go to either a case statement or the default command. The following code snippet shows the switch statement from the previous section executed with goto statements instead of simply dropping through:
switch (roll)
{
case 1:
goto case 4;
break;
case 2:
goto case 5;
break;
case 3:
goto case 4;
break;
case 4:
System.Console.WriteLine(“Roll is Odd”);
break;
case 5:
System.Console.WriteLine(“Roll is Even”);
break;
default:
System.Console.WriteLine(“Roll is not 1 through 6”);
break;
}
ITERATION STATEMENTS :
An Iteration statement repeats a statement or a block of statements until a given termination condition is met.
C# provides a number of iteration statements.The iteration statements in C# are listed here:
- while
- do
- for
- foreach
The while loop repeats a statement or compound statement again and again, here referred as loop body, as long as its associate loop condition, consisting of a Boolean expression, is true. When the loop conditions is false while being evaluated, flow of control moves to the line immediately following the while loop.
Syntax :
while ( condition )
{
Statement(s);
}
Example :
class WhileTest
{
public static void Main()
{
int n = 1;
while (n < 5)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
} }}
OUTPUT :
Current value of n is 1 Current value of n is 2 Current value of n is 3 Current value of n is 4 THE DO-WHILE LOOP STATEMENT : The do-while loop is analogous to the while loop in that the loop body is repeatedly executed over and over again as long as the Boolean expression is True.One important difference is that the loop body is located between the keywords do and while is executed before the Boolean expression is evaluated. Consequently, the loop body of the do-while loop is always executed at least once, even if the Boolean expression is false initially. Example : class Do-WhileTest { public static void Main() { int n = 1; do { Console.WriteLine("Current value of n is {0}", n); n++; }while (n < 5) } } OUTPUT : Current value of n is 1 Current value of n is 2 Current value of n is 3 Current value of n is 4 THE FOR LOOP STATEMENT : The three key components of a loop are as follows
- Loop Condition - When evaluated to true, will cause the loop body to be repeated.
- Loop Initialization - During the loop initialization the variable(s) taking part in the loop condition are assigned initial suitable values.This process only takes place once before the loop commences.
- Loop Update - Updates the variables of the loop condition. This is repeatedly done during every loop.
Example :
class For
{
public static void Main()
{
int n = 1;
for(n=1;n<5;n++)
{
Console.WriteLine("Current value of n is {0}", n); }
Console.ReadLine(); }
}
OUTPUT :
Current value of n is 1
Current value of n is 2
Current value of n is 3
Current value of n is 4
THE FOREACH LOOP STATEMENT :
The foreach loop in C# executes a block of code on each element in an array or a collection of items. When executing foreach loop it traverse items
in a collection or an array. The foreach loop is used for traversing each items in an array or a collection of items and displayed one by one.
Example :
using System;
class Program
{
static void Main()
{
// Use a string array to loop over.
string[] ferns = { "Psilotopsida", "Equisetopsida", "Marattiopsida", "Polypodiopsida" };
// Loop with the foreach keyword.
foreach (string value in ferns)
{
Console.WriteLine(value);
}
}
}
OUTPUT :
Psilotopsida
Equisetopsida
Marattiopsida
Polypodiopsida
Subscribe to:
Comments (Atom)