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

Suppose you have a 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(); } } 

It is acceptable? Or is this error prone or bad practice? I will almost always use IEnumerator<T >, but I still want the non-universal version to be stable and correctly implemented.

+6
c # ienumerable
source share
3 answers

This is completely standard and dry and other problems are recommended.

note that

 return strand; 

it should be

 yield return strand; 

Also, it looks like this.Strands already implements IEnumerable<FurStrand> , so you can just say

 return this.Strands.GetEnumerator(); 
+10
source share

No, that’s perfectly acceptable. Recommended even.

+5
source share

This is not only good practice, but your project will not run without it, because IEnumerable<T> inherits IEnumerable . Take a look at the definition of IEnumerable<T> :

 public interface IEnumerable<out T> : IEnumerable IEnumerator<T> GetEnumerator(); } 

Do you need to implement a non-generic version or you will get the error message "... does not implement the interface element ..."

+4
source share

All Articles