Why the Enumerator of List<T> is public?

What is the reason for the public access modifier on the Enumerator in List?

I would expect private modifier instead of public.

List source code

Jon Skeet
people
quotationmark

It's public so that the GetEnumerator() method can be declared to return it.

That then allows the C# compiler to use it in a foreach loop... avoiding any heap allocations because List.Enumerator is a struct. (A mutable struct, which makes me go "urgh!" but that's another story.)

So when you have something like:

List<string> list = new List<string> { "..." };
foreach (var item in list)
{
    Console.WriteLine(item);
}

Then the compiler can convert it into something like:

List<string> list = new List<string> { "..." };
using (List.Enumerator<string> enumerator = list.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        string item = enumerator.Current;
        Console.WriteLine(item);
    }
}

Note the type of enumerator here - whereas if we had:

IEnumerable<string> list = new List<string> { "..." };
foreach (var item in list)
{
    Console.WriteLine(item);
}

it would use:

using (IEnumerator<string> enumerator = list.GetEnumerator())

... which involves a heap allocation as IEnumerator<string> is a reference type. The IEnumerable<T> implementation of GetEnumerator() in List<T> returns a boxed List.Enumerator<string>.

people

See more on this question at Stackoverflow