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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With