Reputation: 331460
Basically suppose you have some collection:
public class FurCollection : IEnumerable<FurStrand>
{
public IEnumerator<FurStrand> GetEnumerator()
{
foreach(var strand in this.Strands)
{
yield return strand;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
Is this acceptable? Or is this bug-prone or bad practice? I will pretty much always be using the IEnumerator<T
> but I still want the non-generic version to be stable and properly implemented.
Upvotes: 6
Views: 1048
Reputation: 24344
Not only is this good practice, but your project will not complile without it, because IEnumerable<T>
inherits IEnumerable
. Look at the definition of IEnumerable<T>
:
public interface IEnumerable<out T> : IEnumerable
IEnumerator<T> GetEnumerator();
}
You have to implement the non-generic version or you'll get an error "... does not implement interface member..."
Upvotes: 4
Reputation: 241779
This is completely standard and recommended to comply with DRY and other concerns.
Note that
return strand;
should be
yield return strand;
Additionally, it looks like this.Strands
already implements IEnumerable<FurStrand>
so you could just say
return this.Strands.GetEnumerator();
Upvotes: 10