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?
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>();
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