What is Ienumerable.Getenumerator in C#?

Asked

Viewed 97 times

1

I was reading this documentation and I came across the following piece of code within a class that implements IEnumerable:

// Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator()
{
    return (IEnumerator) GetEnumerator();
}

But what exactly is this IEnumerable.GetEnumerator? I know that IEnumerable is an interface, but there GetEnumerator would be a property of that interface?

The doubt was because usually put the name of the method in the place where it is IEnumerable.GetEnumerator. In that sense, I see the name of a method as something concrete, then how could an "interface property" play this role? It would be something like a special name?

1 answer

1


GetEnumerator() ends with parentheses, right? And if you have this, as in all languages, it would be a... method!

What seems strange is having a surname in the method. And this is what is called explicit implementation of interface. It is a special way to name the implementation as it shows details in link.

Today it can be written like this:

IEnumerator IEnumerable.GetEnumerator() => (IEnumerator)GetEnumerator();

We have here the type of return, the name of the method preceded by which is the interface he is making the implementation, which differentiates from the standard implementation of the type itself, and then the body that just calls another existing method in the class making a cast to make the return of this method compatible.

If it did not break compatibility every enumeration system of C# would be redone, has errors in the whole idea, is one of the biggest problems of the language, and that most people do not even notice.

  • Thank you for the answer! : -) I was curious about the problems of the enumeration system of C#, you have some reference so I can understand them better?

  • 1

    These things you will see with accumulation of information, but not to say that you have nothing, I will give an example: https://blog.paranoidcoding.com/2014/08/19/rethinking-enumerable.html and https://github.com/dotnet/csharplang/issues/1931 and https://stackoverflow.com/q/23536541/221800 and https://www.monitis.com/blog/how-c-ienumerable-can-Kill-your-sites-performance/ and https://www.reddit.com/r/csharp/comments/9paafp/enumerators_avoiding_bad_usage/. Because of this there are situations that occur Boxing without the programmer noticing and without needing because in general could be a type by value.

  • 1

    So they have even been improving at one point or another, for example: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/extension-getenumerator. And there are already cases that the compiler does optimizations. See: https://github.com/dotnet/csharplang/discussions/378

Browser other questions tagged

You are not signed in. Login or sign up in order to post.