Question

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?

Was it helpful?

Solution

This is a bad idea because the solution will break down if someone attempts to enumerate your collection more than once at the same time.

For example: This will break in some way

For Each cur1 in yourObj 
  For Each cur2 in yourObj
    Console.WriteLine("{0} - {1}", cur1,cur2)
  Next
Next

OTHER TIPS

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 :)

From Implementing IEnumerable:

Do provide a GetEnumerator() method that returns a nested public struct called “Enumerator”.

By the way, this website is maintained by Brad Abrams - one of the authors of Framework Design Guidelines.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top