Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic IEnumerable

I'm learning about the iterator pattern under the hood so eventually I can use it in some classes. Here's a test class:

public class MyGenericCollection : IEnumerable<int>
{
    private int[] _data = { 1, 2, 3 };

    public IEnumerator<int> GetEnumerator()
    {
        foreach (int i in _data)
        {
            yield return i;
        }
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

I'm confused on the IEnumerable.GetEnumerator() section. In the code tests that I've ran, it's never referenced or used, but I have to have it to implement the generic IEnumerable.

I do understand that IEnumerable<T> inherits from IEnumerator, so that I have to implement both.

Outside of that I'm confused when the non-generic interface is ever used. In debugging it's never entered. Can anyone help me understand?

like image 483
Birdman Avatar asked Oct 20 '25 15:10

Birdman


1 Answers

I'm confused on the IEnumerable.GetEnumerator() section. In the code tests that I've ran, it's never referenced or used, but I have to have it to implement the generic IEnumerable.

It would be used by anything that used your type as just an IEnumerable. For example:

IEnumerable collection = new MyGenericCollection();
// This will call the GetEnumerator method in the non-generic interface
foreach (object value in collection)
{
    Console.WriteLine(value);
}

There are just a few LINQ methods that would call it, too: Cast and OfType:

var castCollection = new MyGenericCollection().OfType<int>();
like image 156
Jon Skeet Avatar answered Oct 23 '25 03:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!