Joan Venge
Joan Venge

Reputation: 331460

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.

Upvotes: 6

Views: 1048

Answers (3)

Jamie Treworgy
Jamie Treworgy

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

jason
jason

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

Mark H
Mark H

Reputation: 13907

No, this is perfectly acceptable. Recommended even.

Upvotes: 5

Related Questions