Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable and IEnumerator in the same class, bad idea?

Is this a bad idea?

Private Class GH_DataStructureEnumerator(Of Q As Types.IGH_Goo)
  Implements IEnumerable(Of Q)
  Implements IEnumerator(Of Q)
  ....
  ....
  'Current, MoveNext, Reset etc.'
  ....
  ....

  Public Function GetEnumerator_Generic() As IEnumerator(Of Q) _
                  Implements IEnumerable(Of Q).GetEnumerator
    Return Me
  End Function
End Class

This class is only visible as an IEnumerable(Of T) readonly property, and it saves me an additional class that wraps IEnumerator(Of T). But somehow it just seems wrong. Is there a better way?

like image 735
David Rutten Avatar asked Mar 25 '10 20:03

David Rutten


1 Answers

Definitely a bad idea. In particular, it means that two calls to GetEnumerator will return references to the same object - when they should return independent iterators.

Now having said that, the C# compiler will generate classes which implement both types if you use iterator blocks... but it goes to great lengths to make sure that it gets it right. I suggest you don't put yourself through that pain :)

like image 130
Jon Skeet Avatar answered Oct 09 '22 19:10

Jon Skeet