Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the Enumerator of List<T> is public?

Tags:

c#

.net

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

like image 774
Nikola Nikolov Avatar asked Mar 11 '16 11:03

Nikola Nikolov


1 Answers

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.

like image 106
Jon Skeet Avatar answered Sep 21 '22 11:09

Jon Skeet