Foreach Loop
suggest changeforeach iterates any object that implements IEnumerable (IEnumerable<T> inherits from it), and also any type that exposes a suitable GetEnumerator method. Built-in examples include List<T>, arrays, Dictionary<TKey, TValue>, IQueryable, and ICollection.
syntax
foreach(ItemType itemVariable in enumerableObject)
statement;
remarks
ItemTypedoes not have to be the exact element type. The element must be convertible toItemType.varmay replaceItemType. The compiler infers the type from the enumerator'sCurrentproperty.- The statement can be a block, a single statement, or an empty statement (
;). - The compiler accepts the object when it finds a public
GetEnumeratormethod. ImplementingIEnumerableis the usual way to provide that method, but it is not the only way. - If
ItemTypeis not the type ofCurrent, the element is converted. A failing reference conversion throwsInvalidCastException. Withvar, the variable already has the type ofCurrent, so there is no extra cast.
Consider this example:
var list = new List<string>();
list.Add("Ion");
list.Add("Andrei");
foreach(var name in list)
{
Console.WriteLine("Hello " + name);
}
is equivalent to:
var list = new List<string>();
list.Add("Ion");
list.Add("Andrei");
using (var enumerator = list.GetEnumerator())
{
while (enumerator.MoveNext())
{
string name = enumerator.Current;
Console.WriteLine("Hello " + name);
}
}
List<string>.GetEnumerator() returns a struct whose Current is already a string, so the expansion does not cast. A non-generic IEnumerator exposes Current as object, and the foreach expansion then casts it to the iteration type.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents