Nikola Nikolov
Nikola Nikolov

Reputation: 1310

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

Upvotes: 16

Views: 668

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500903

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<string>.Enumerator 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<string>.Enumerator.

Upvotes: 30

Patrick Hofman
Patrick Hofman

Reputation: 156988

Simply because it is reused in a lot of other assemblies.

You can discuss whether that is a valid reason to use the struct and not the underlying interface, but that is the foremost reason I guess.

Upvotes: 1

Related Questions