Saturday, September 26, 2009

Constructors


CONSTRUCTORS
One of the biggest advantages of an object-oriented programming (OOP) language such as C# is that you can define special methods that are called whenever an instance of the class is created. These methods are called constructors. C# introduces a new type of constructor called a static constructor, which you’ll see in the next section, “Static Members and Instance Members.”
A key benefit of using a constructor is that it guarantees that the object will go through proper initialization before being used. When a user instantiates an object, that object’s constructor is called and must return before the user can perform any other work with that object. This guarantee helps ensure the integrity of the object and helps make applications written with object-oriented languages much more reliable.
But how do you name a constructor so that the compiler will know to call it when the object is instantiated? The C# designers followed the lead of the C++ language designer, Bjarne Stroustrup, and dictated that constructors in C# must have the same name as the class itself. Here’s a simple class with an equally simple constructor:
using System;

class Constructor1App
{
    Constructor1App()
    {
        Console.WriteLine("[Constructor1App.Constructor1App] " +
            "I'm the constructor");
    }

    public static void Main()
    {
        Console.WriteLine("\n[Main] Instantiating a " +
            "Constructor1 object...");
        Constructor1App app = new Constructor1App();
    }
}
Constructors don’t return values. If you attempt to prefix the constructor with a type, the compiler will issue an error stating that you can’t define a member with the same name as the enclosing type.
You should also note the way objects are instantiated in C#. This is done using the new keyword with the following syntax:
<class> <object> = new <class>(constructor arguments)
If you come from a C++ background, pay special attention to this. In C++, you can instantiate an object in two ways. You can declare it on the stack, like this:
// C++ code. This creates an instance of CMyClass on the stack.
CMyClass myClass;
Or you can instantiate the object on the free store (or heap) by using the C++ new keyword:
// C++ code. This creates an instance of CMyClass on the heap.
CMyClass myClass = new CMyClass();
Instantiating objects is different in C# than it is in C++, and this difference is a cause for confusion for new C# developers. The confusion stems from the fact that both languages share a common keyword for creating objects. Although using the new keyword in C++ lets you dictate where an object gets created, where an object is created in C# depends upon the type being instantiated.  Having said that, the following code is valid C# code, but if you’re a C++ developer, it might not do what you expect it too:
MyClass myClass;
In C++, this code would create an instance of MyClass on the stack. As mentioned, you can create objects in C# only by using the new keyword. Therefore, this line of code in C# merely declares that myClass is a variable of type MyClass, but it doesn’t instantiate the object.
As an example of this, if you compile the following program, the C# compiler will warn you that the variable has been declared but isn’t used in the application.  
using System;

class Constructor2App
{
    Constructor2App()
    {
        Console.WriteLine("[Constructor2App.Constructor2App] " +
            "I'm the constructor");
    }

    public static void Main()
    {
        Console.WriteLine("\n[Main] Declaring, but not " +
            "instantiating, a Constructor2 object..."); 
        Constructor2App app;
    }
}
Therefore, if you declare an object type, you need to instantiate it somewhere in your code by using the new keyword:
Constructor2App app;
app = new Constructor2App();
Why would you declare an object without instantiating it? Declaring objects before using them—or “new-ing“ them—is done in cases in which you declare one class inside another. This nesting of classes is called containment, or aggregation. For example, I might have an Invoice class that has several embedded classes, such as Customer, TermCode, and SalesTaxCode.
Static Members and Instance Members
As with C++, you can define a member of a class as a static member or an instance member. By default, each member is defined as an instance member, which means that a copy of that member is made for every instance of the class. When you declare a member a static member, only one copy of the member exists. A static member is created when the application containing the class is loaded, and it exists throughout the life of the application. Therefore, you can access the member even before the class has been instantiated. But why would you do this?
One example involves the Main method. The common language runtime needs to have a common entry point to your application. You must define a static method called Main in one of your classes so that the runtime doesn’t have to instantiate one of your objects. You also use static members when you have a method that, from an object-oriented perspective, belongs to a class in terms of semantics but doesn’t need an actual object—for example, if you want to keep track of how many instances of a given object are created during the lifetime of an application. Because static members live across object instances, the following code would work:
using System;

class InstCount
{
    public InstCount()
    {
        instanceCount++;
    }

    static public int instanceCount;
    // instanceCount = 0;
}

class AppClass
{
    public static void PrintInstanceCount()
    {
        Console.WriteLine("[PrintInstanceCount] Now there {0} " +
            "{1} instance{2} of the InstCount class", 
            InstCount.instanceCount == 1 ? "is" : "are",
            InstCount.instanceCount,
            InstCount.instanceCount == 1 ? "" : "s");
    }

    public static void Main()
    {
        PrintInstanceCount();

        InstCount ic;
        for (int i = 0; i < 2; i++)
        {
            ic = new InstCount();
            Console.WriteLine("[Main] Instantiated a " +
                "{0} object...", ic.GetType());

            PrintInstanceCount();
        }
    }
}

If you build and run this application, you’ll see the results shown in following Figure

One last note on static members that are value types: a static member must have a valid value. You can specify this value when you define the member, as follows:
static public int instanceCount1 = 10;
If you don’t initialize the variable, the common language runtime will do so upon application startup by using a default value of 0. Therefore, the following two lines are equivalent:
static public int instanceCount2;
static public int instanceCount2 = 0;


Constants vs. Read-Only Fields
There will certainly be times when you have fields that you don’t want altered during the execution of the application. Examples of fields you might want to protect include the names of data files your application depends on, certain unchanging values for a math class such as pi, or even server names and IP addresses that your computer connects to. Obviously, this list could go on ad infinitum. To address these situations, C# allows for the definition of two closely related member types: constants and read-only fields, which I’ll cover in this section.
Constants
As you can guess from the name, constants—represented by the const keyword—are fields that remain constant for the life of the application. There are only three rules to keep in mind when defining something as a const:
  • A constant is a member whose value is set at compile time.
  • A constant member’s value must be written as a literal.
  • To define a field as a constant, simply specify the const keyword before the member being defined, as follows:
using System;

class MagicNumbers
{
    public const double pi = 3.1415;
    public const int answerToAllLifesQuestions = 42;
}

class ConstApp
{
    public static void Main()
    {
        Console.WriteLine("CONSTANTS: pi = {0},"
           "everything else = {1}",
            MagicNumbers.pi, 
            MagicNumbers.answerToAllLifesQuestions);
    }
}

Read-Only Fields
A field defined as a const is useful because it clearly documents the programmer’s intention that the field contains an immutable value. However, that works only if you know the value at compile time. So what does a programmer do when the need arises for a field with a value that won’t be known until run time and shouldn’t be changed once it’s been initialized? This issue—typically not addressed in other languages—was resolved by the designers of the C# language with what’s called a read-only field.
When you define a field with the readonly keyword, you have the ability to set that field’s value in one place: the constructor. After that point, the field can’t be changed by the class itself or the class’s clients. Let’s say that your application needs to keep track of the current workstation’s IP address. You wouldn’t want to address this problem with a const because that would entail hard-coding the value—and even that technique wouldn’t work if the workstation obtains its IP address dynamically. However, a run-time field would do just the trick:
using System;
using System.Net;

class Workstation
{
    public Workstation()
    {
        IPAddress ipAddress =
            Dns.Resolve(HostName).AddressList[0];
        IPAddressString = ipAddress.ToString();
    }

    public const string HostName = "tyagi";
    public readonly string IPAddressString;
}

class GetIpAddress
{
    public static void Main()
    {
        Workstation workstation = new Workstation();
        Console.WriteLine("The IP address for '{0}' is {1}",
            Workstation.HostName, workstation.IPAddressString);

    }
}

Running this application will result in the display of the IP address associated with the supplied host name (tyagi). Obviously, this program won’t work correctly if you aren’t connected to a machine with a host name of “tyagi”. To specify the name of the machine to which you’re connected, simply modify the WorkStation class’s const field (HostName) to the name of the machine whose IP address you’re attempting to determine. Supply your PC’s machine name for your own workstation IP address.

Wednesday, July 8, 2009

EXCEPTION HANDLING



Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution. 

C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.

The general form try-catch-finally in C# is shown below 

try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}

If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.

But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. 

If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto. 

In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc. 

Uncaught Exceptions 

The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can't find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program. 

//C#: Exception Handling
//Author: rajeshvs@msn.com
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 100/x;
Console.WriteLine(div);
}
}

The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero. 

//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("This line in not executed");
}
catch(DivideByZeroException de)
{
Console.WriteLine("Exception occured");
}
Console.WriteLine("Result is {0}",div);
}
}

In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements.
If a finally block is present, the code inside the finally block will get also be executed.  

//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("Exception occured");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.

//C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block.

Multiple Catch Blocks 

A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error. 

//C#: Exception Handling: Multiple catch
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ee)
{
Console.WriteLine("Exception" );
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}

Catching all Exceptions

By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.  

//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}
}

The following program handles all exception with Exception object.

//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(Exception e)
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}
}

Throwing an Exception

In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this purpose. The general form of throwing an exception is as follows.

throw exception_obj;

For example the following statement throw an ArgumentException explicitly.

throw new ArgumentException("Exception");

//C#: Exception Handling:
using System;
class MyClient
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception" );
}
Console.WriteLine("LAST STATEMENT");
}
}

Re-throwing an Exception

The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the keyword throw inside the catch block. The following program shows how to do this. 

//C#: Exception Handling: Handling all exceptions
using System;
class MyClass
{
public void Method()
{
try
{
int x = 0;
int sum = 100/x;
}
catch(DivideByZeroException e)
{
throw;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
try
{
mc.Method();
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" );
}
Console.WriteLine("LAST STATEMENT");
}
}

Standard Exceptions

There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc.

The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.
  •  
System.OutOfMemoryException
  • System.NullReferenceException
  • Syste.InvalidCastException
  • Syste.ArrayTypeMismatchException
  • System.IndexOutOfRangeException        
  • System.ArithmeticException
  • System.DevideByZeroException
  • System.OverFlowException 
User-defined Exceptions

In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.

//C#: Exception Handling: User defined exceptions
using System;
class MyException : Exception
{
public MyException(string str)
{
Console.WriteLine("User defined exception");
}
}
class MyClient
{
public static void Main()
{
try
{
throw new MyException("RAJESH");
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" + e.ToString());
}
Console.WriteLine("LAST STATEMENT");
}
}

Design Guidelines

Exceptions should be used to communicate exceptional conditions. Don't use them to communicate events that are expected, such as reaching the end of a file. If there's a good predefined exception in the System namespace that describes the exception condition-one that will make sense to the users of the class-use that one rather than defining a new exception class, and put specific information in the message. Finally, if code catches an exception that it isn't going to handle, consider whether it should wrap that exception with additional information before re-throwing it.


Wednesday, June 24, 2009

FLOW CONTROL


Conditional Statements
Conditional statements allow you to branch your code depending on whether certain conditions are met or on the value of an expression. C# has two constructs for branching code — the if statement, which allows you to test whether a specific condition is met, and the switch statement, which allows you to compare an expression with a number of different values.
The if statement
For conditional branching, C# inherits the C and C++ if...else construct. The syntax should be fairly intuitive for anyone who has done any programming with a procedural language:
if (condition)
   statement(s)
else
   statement(s)
If more than one statement is to be executed as part of either condition, these statements will need to be joined together into a block using curly braces ({ ... }). (This also applies to other C# constructs where statements can be joined into a block, such as the for and while loops):
bool isZero;
if (i == 0)
{
isZero = true;
Console.WriteLine("i is Zero");
}
else
{
isZero = false;
Console.WriteLine("i is Non-zero");
}
The syntax here is similar to C++ and Java but once again different from Visual Basic. Visual Basic developers should note that C# does not have any statement corresponding to Visual Basic's EndIf. Instead, the rule is that each clause of an if contains just one statement. If you need more than one statement, as in the preceding example, you should enclose the statements in braces, which will cause the whole group of statements to be treated as a single block statement.
If you want to, you can use an if statement without a final else statement. You can also combine else if clauses to test for multiple conditions:
using System;

class MainEntryPoint
{
 static void Main(string[] args)
 {
Console.WriteLine("Type in a string");
string input;
input = Console.ReadLine();
if (input == "")
{
Console.WriteLine("You typed in an empty string");
}
else if (input.Length < 5)
{
Console.WriteLine("The string had less than 5 characters");
}
else if (input.Length < 10)
{
Console.WriteLine("The string had at least 5 but less than 10
characters");
}
Console.WriteLine("The string was " + input);
      }
   }

There is no limit to how many else if's you can add to an if clause.
You'll notice that the previous example declares a string variable called input, gets the user to enter text at the command line, feeds this into input, and then tests the length of this string variable. The code also shows how easy string manipulation can be in C#. To find the length of input, for example, use input.Length.
One point to note about if is that you don't need to use the braces if there's only one statement in the conditional branch:
if (i == 0)
Console.WriteLine("i is Zero");       // This will only execute if i == 0
Console.WriteLine("i can be anything");  // Will execute whatever the
// value of i
However, for consistency, many programmers prefer to use curly braces whenever they use an if statement.
The if statements presented also illustrate some of the C# operators that compare values. Note in particular that, like C++ and Java, C# uses == to compare variables for equality. Do not use = for this purpose. A single = is used to assign values.
In C#, the expression in the if clause must evaluate to a Boolean. C++ programmers should be particularly aware of this; unlike C++, it is not possible to test an integer (returned from a function, say) directly. In C#, you have to convert the integer that is returned to a Boolean true or false, for example by comparing the value with zero or with null:
if (DoSomething() != 0)
{
// Non-zero value returned
}
else
{
// Returned zero
}
This restriction is there in order to prevent some common types of runtime bugs that occur in C++. In particular, in C++ it was common to mistype = when == was intended, resulting in unintentional assignments. In C# this will normally result in a compile-time error, because unless you are working with bool values, = will not return a bool.
The switch statement
The switch...case statement is good for selecting one branch of execution from a set of mutually exclusive ones. It will be familiar to C++ and Java programmers and is similar to the Select Case statement in Visual Basic.
It takes the form of a switch argument followed by a series of case clauses. When the expression in the switch argument evaluates to one of the values beside a case clause, the code immediately following the case clause executes. This is one example where you don't need to use curly braces to join statements into blocks; instead, you mark the end of the code for each case using the break statement. You can also include a default case in the switch statement, which will execute if the expression evaluates to none of the other cases. The following switch statement tests the value of the integerA variable:
switch (integerA)
{
case 1:
Console.WriteLine("integerA =1");
break;
case 2:
Console.WriteLine("integerA =2");
break;
case 3:
Console.WriteLine("integerA =3");
break;
default:
Console.WriteLine("integerA is not 1,2, or 3");
break;
}
Note that the case values must be constant expressions; variables are not permitted.
Though the switch...case statement should be familiar to C and C++ programmers, C#'s switch...case is a bit safer than its C++ equivalent. Specifically, it prohibits fall-through conditions in almost all cases. This means that if a case clause is fired early on in the block, later clauses cannot be fired unless you use a goto statement to mark that you want them fired too. The compiler enforces this restriction by flagging every case clause that is not equipped with a break statement as an error similar to this:
Control cannot fall through from one case label ('case 2:') to another
Although it is true that fall-through behavior is desirable in a limited number of situations, in the vast majority of cases it is unintended and results in a logical error that's hard to spot. Isn't it better to code for the norm rather than for the exception?
By getting creative with goto statements (which C# does support) however, you can duplicate fall-through functionality in your switch...cases. However, if you find yourself really wanting to, you probably should reconsider your approach. The following code illustrates both how to use goto to simulate fall- through, and how messy the resultant code can get:
// assume country and language are of type string
switch(country)
{
case "America":
CallAmericanOnlyMethod();
goto case "Britain";
case "France":
language = "French";
break;
case "Britain":
language = "English";
break;
}
There is one exception to the no–fall-through rule, however, in that you can fall through from one case to the next if that case is empty. This allows you to treat two or more cases in an identical way (without the need for goto statements):
switch(country)
{
case "au":
case "uk":
case "us":
language = "English";
break;
case "at":
case "de":
language = "German";
break;
}
One intriguing point about the switch statement in C# is that the order of the cases doesn't matter — you can even put the default case first! As a result, no two cases can be the same. This includes different constants that have the same value, so you can't, for example, do this:
// assume country is of type string
const string england = "uk";
const string britain = "uk";
switch(country)
{
case england:
case britain:    // this will cause a compilation error
language = "English";
break;
}
The previous code also shows another way in which the switch statement is different in C# from C++: In C#, you are allowed to use a string as the variable being tested.
Loops
C# provides four different loops (for, while, do...while, and foreach) that allow you to execute a block of code repeatedly until a certain condition is met. The for, while, and do...while loops are essentially identical to those encountered in C++.
The for loop
C# for loops provide a mechanism for iterating through a loop where you test whether a particular condition holds before you perform another iteration. The syntax is
for (initializer; condition; iterator)
   statement(s)
where
  • The initializer is the expression evaluated before the first loop is executed (usually initializing a local variable as a loop counter).
  • The condition is the expression checked before each new iteration of the loop (this must evaluate to true for another iteration to be performed).
  • The iterator is an expression evaluated after each iteration (usually incrementing the loop counter). The iterations end when the condition evaluates to false.
The for loop is a so-called pre-test loop, because the loop condition is evaluated before the loop statements are executed, and so the contents of the loop won't be executed at all if the loop condition is false.
The for loop is excellent for repeating a statement or a block of statements for a predetermined number of times. The following example is typical of the use of a for loop. The following code will write out all the integers from 0 to 99:
for (int i = 0; i < 100; i = i+1)   // this is equivalent to
// For i = 0 To 99 in VB.
{
Console.WriteLine(i);
}
Here, you declare an int called i and initialize it to zero. This will be used as the loop counter. You then immediately test whether it is less than 100. Because this condition evaluates to true, you execute the code in the loop, displaying the value 0. You then increment the counter by one, and walk through the process again. Looping ends when i reaches 100.
Actually, the way the preceding loop is written isn't quite how you would normally write it. C# has a shorthand for adding 1 to a variable, so instead of i=i+1, you can simply write i++:
for (int i = 0; i < 100; i++)
{
    // etc.
C# for loop syntax is far more powerful than the Visual Basic For...Next loop, because the iterator can be any statement. In Visual Basic, all you can do is add or subtract some number from the loop control variable. In C# you can do anything; for example, you can multiply the loop control variable by 2.
It's not unusual to nest for loops so that an inner loop executes once completely for each iteration of an outer loop. This scheme is typically employed to loop through every element in a rectangular multidimensional array. The outermost loop loops through every row, and the inner loop loops through every column in a particular row. The following code displays rows of numbers. It also uses another Console method, Console.Write(), which does the same as Console.WriteLine() but doesn't send a carriage return to the output.
using System;


   class MainEntryPoint
   {
      static void Main(string[] args)
      {
// This loop iterates through rows...
for (int i = 0; i < 100; i+=10)
{
// This loop iterates through columns...
for (int j = i; j < i + 10; j++)
{
Console.Write("  " + j);
}
Console.WriteLine();
}
      }
   }

Although j is an integer, it will be automatically converted to a string so that the concatenation can take place. C++ developers will note that this is far easier than string handling ever was in C++; for Visual Basic developers this is familiar ground.
C programmers should take note of one particular feature of the preceding example. The counter variable in the innermost loop is effectively re-declared with each successive iteration of the outer loop. This syntax is legal not only in C# but in C++ as well.
The preceding sample results in this output:

0  1  2 3  4  5  6  7  8  9
10  11  12  13  14  15  16  17  18  19
20  21  22  23  24  25  26  27  28  29
30  31  32  33  34  35  36  37  38  39
40  41  42  43  44  45  46  47  48  49
50  51  52  53  54  55  56  57  58  59
60  61  62  63  64  65  66  67  68  69
70  71  72  73  74  75  76  77  78  79
80  81  82  83  84  85  86  87  88  89
90  91  92  93  94  95  96  97  98  99
Although it is technically possible to evaluate something other than a counter variable in a for loop's test condition, it is certainly not typical. It is also possible to omit one (or even all) of the expressions in the for loop. In such situations, however, you should consider using the while loop.
The while loop
The while loop is identical to the while loop in C++ and Java, and the While...Wend loop in Visual Basic. Like the for loop, while is a pre-test loop. The syntax is similar, but while loops take only one expression:
while(condition)
statement(s);
Unlike the for loop, the while loop is most often used to repeat a statement or a block of statements for a number of times that is not known before the loop begins. Usually, a statement inside the while loop's body will set a Boolean flag to false on a certain iteration, triggering the end of the loop, as in the following example:
bool condition = false;
while (!condition)
{
// This loop spins until the condition is true
DoSomeWork();
condition = CheckCondition();   // assume CheckCondition() returns a bool
}
All of C#'s looping mechanisms, including the while loop, can forego the curly braces that follow them if they intend to repeat just a single statement and not a block of statements. Again, many programmers consider it good practice to use braces all of the time.
The do...while loop
The do...while loop is the post-test version of the while loop. It does the same thing with the same syntax as do...while in C++ and Java, and the same thing as Loop...While in Visual Basic. This means that the loop's test condition is evaluated after the body of the loop has been executed. Consequently,do...while loops are useful for situations in which a block of statements must be executed at least one time, as in this example:
bool condition;
do
{
// this loop will at least execute once, even if Condition is false
MustBeCalledAtLeastOnce();
condition = CheckCondition();
} while (condition);
The foreach loop
The foreach loop is the final C# looping mechanism that we discuss. Whereas the other looping mechanisms were present in the earliest versions of C and C++, the foreach statement is a new addition (bor- rowed from Visual Basic), and a very welcome one at that.
The foreach loop allows you to iterate through each item in a collection.  Technically, to count as a collection, it must support an interface called IEnumerable. Examples of collections include C# arrays, the collection classes in the System.Collection namespaces, and user-defined collection classes. You can get an idea of the syntax of foreach from the following code, if you assume that arrayOfInts is (unsurprisingly) an array if ints:
foreach (int temp in arrayOfInts)
{
Console.WriteLine(temp);
}
Here, foreach steps through the array one element at a time. With each element, it places the value of the element in the int variable called temp, and then performs an iteration of the loop.
An important point to note with foreach is that you can't change the value of the item in the collection (temp in the preceding code), so code such as the following will not compile:
foreach (int temp in arrayOfInts)
{
temp++;
Console.WriteLine(temp);
}
If you need to iterate through the items in a collection and change their values, you will need to use a for loop instead.
Jump Statements
C# provides a number of statements that allow you to jump immediately to another line in the program. The first of these is, of course, the notorious goto statement.
The goto statement
The goto statement allows you to jump directly to another specified line in the program, indicated by a label (this is just an identifier followed by a colon):
goto Label1;
Console.WriteLine("This won't be
Label1:
Console.WriteLine("Continuing execution from here");
A couple of restrictions are involved with goto. You can't jump into a block of code such as a for loop, you can't jump out of a class, and you can't exit a finally block after try...catch blocks.
The reputation of the goto statement probably precedes it, and in most circumstances, its use is sternly frowned upon. In general, it certainly doesn't conform to good object-oriented programming practice. However, there is one place where it is quite handy: jumping between cases in a switch statement, particularly because C#'s switch is so strict on fall-through. You saw the syntax for this earlier in this chapter.
The break statement
You have already met the break statement briefly — when you used it to exit from a case in a switch statement. In fact, break can also be used to exit from for, foreach, while, or do...while loops too. Control will switch to the statement immediately after the end of the loop.
If the statement occurs in a nested loop, control will switch to the end of the innermost loop. If the break occurs outside of a switch statement or a loop, a compile-time error will occur.
The continue statement
The continue statement is similar to break, and must also be used within a for, foreach, while, or do...while loop. However, it exits only from the current iteration of the loop, meaning execution will restart at the beginning of the next iteration of the loop, rather than outside the loop altogether.
The return statement
The return statement is used to exit a method of a class, returning control to the caller of the method. If the method has a return type, return must return a value of this type; otherwise if the method returns void, you should use return without an expression.