Thursday, June 30, 2011

Foreach in c sharp


Foreach in  csharp
The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.
http://i.msdn.microsoft.com/Hash/030c41d9079671d09a62d8e2c1db6973.gifRemarks


The embedded statements continue to execute for each element in the array or collection. After the iteration has been completed for all the elements in the collection, control is transferred to the next statement following the foreach block.
At any point within the foreach block, you can break out of the loop using the break keyword, or step directly to the next iteration in the loop by using thecontinue keyword.
A foreach loop can also be exited by the goto, return, or throwstatements.
In this example, foreach is used to display the contents of an array of integers.
// cs_foreach.cs
class ForEachTest
{
    static void Main(string[] args)
    {
        int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
        foreach (int i in fibarray)
        {
            System.Console.WriteLine(i);
        }
    }
}
Output

0
1
2
3
5
8
13
Foreach using arrays:
int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
    System.Console.WriteLine(i);
}
int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}

No comments:

Post a Comment

Your comment is pending for approval

AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...