Foreach Loop
suggest changeforeach will iterate over any object of a class that implements IEnumerable (take note that IEnumerable<T> inherits from it). Such objects include some built-in ones, but not limit to: List<T>, T[] (arrays of any type), Dictionary<TKey, TSource>, as well as interfaces like IQueryable and ICollection, etc.
syntax
foreach(ItemType itemVariable in enumerableObject)
statement;
remarks
- The type
ItemTypedoes not need to match the precise type of the items, it just needs to be assignable from the type of the items - Instead of
ItemType, alternativelyvarcan be used which will infer the items type from the enumerableObject by inspecting the generic argument of theIEnumerableimplementation - The statement can be a block, a single statement or even an empty statement (
;) - If
enumerableObjectis not implementingIEnumerable, the code will not compile - During each iteration the current item is cast to
ItemType(even if this is not specified but compiler-inferred viavar) and if the item cannot be cast anInvalidCastExceptionwill be thrown.
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");
IEnumerator enumerator;
try
{
enumerator = list.GetEnumerator();
while(enumerator.MoveNext())
{
string name = (string)enumerator.Current;
Console.WriteLine("Hello " + name);
}
}
finally
{
if (enumerator != null)
enumerator.Dispose();
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents