Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to return IEnumerator<T>.GetEnumerator() in IEnumerator.GetEnumerator()?

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.

like image 453
Joan Venge Avatar asked Jan 14 '11 18:01

Joan Venge


3 Answers

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();
like image 117
jason Avatar answered Sep 28 '22 05:09

jason


No, this is perfectly acceptable. Recommended even.

like image 24
Mark H Avatar answered Sep 28 '22 06:09

Mark H


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..."

like image 35
Jamie Treworgy Avatar answered Sep 28 '22 04:09

Jamie Treworgy