Foreach Loop

suggest change

foreach 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

  1. ItemType does not have to be the exact element type. The element must be convertible to ItemType.
  2. var may replace ItemType. The compiler infers the type from the enumerator's Current property.
  3. The statement can be a block, a single statement, or an empty statement (;).
  4. The compiler accepts the object when it finds a public GetEnumerator method. Implementing IEnumerable is the usual way to provide that method, but it is not the only way.
  5. If ItemType is not the type of Current, the element is converted. A failing reference conversion throws InvalidCastException. With var, the variable already has the type of Current, 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents