foreach...in

Foreach is applicable to instances of the IEnumerable type or Generic collections. This works similar to the for loop. Foreach is not just limited to these types; it can also be applied to any instance that implements the GetEnumerator method without parameters and returns a class, struct, or interface type. Foreach can also be applied to types that are returned by the Current property of GetEnumerator and parameter less MoveNext methods, which return a bool value.

From C# 7.3 onward, the Current property returns a reference to the return value (ref T), where T is of the collection element type.

In the following example, we declare the list of strings and would like to iterate through the list and display every item on the screen:

List<string> stringlist = new List<string>() { "One", "Two", "Three" };
foreach (string str in stringlist)
{
Console.WriteLine("Element #"+ str);
}

//Output:
Element #One
Element #Two
Element #Three

IEnumerator has a property called Current and a method called MoveNext. As the foreach loop works to iterate the throw collections that implement these two, it keeps track of which item in the collection is currently being evaluated and processed. This makes sure that control is not passed through the end of the collection. Also, the foreach loop doesn't allow the user to make changes to the initialized loop variable but does allow them to modify the value in the object that's referred to in the variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.239.44