Friday 20 November 2015

The foreach loop in asp.net



Introduction:

C# provides four different loops (for, while, do...while, and foreach) that allow us to execute a block of code repeatedly until a certain condition is met.I will explain about the foreach loop here.
 
Explanation:

The foreach loop allows us to iterate through each item in a collection. For the time being we won’t worry about exactly what a collection is—For now, we will just say that it is an object that contains other objects. 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. We can get an idea of the syntax of foreach from the following
code, if we assume that fruits is  an string array:

string[] fruits = { "apple", "orange", "banana" };

                foreach (string temp in fruits)
        {
            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 string  variable called temp.

Output of the above program:

apple
orange
banana

Foreach is a reserved keyword. The iteration variable "string value" can be a different type. For example, we can use "int number" when looping over ints.

No comments:

Post a Comment