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.
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();
No, this is perfectly acceptable. Recommended even.
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..."
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