Friday, November 24, 2006

Forwarding IEnumerable(Of T)

Often we have a class that implements IEnumerable by returning the enumerator from an embedded list or array:

    1 

    2 Public Class Class1

    3     Implements IEnumerable

    4 

    5     Private Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator

    6         Return _items.GetEnumerator

    7     End Function

    8 

    9     Private _items() As Integer

   10 

   11 End Class

   12 

When I tried to do the same thing with a generic class, I had a problem:

    1 

    2 Public Class Class2(Of X As New)

    3     Implements IEnumerable(Of X)

    4 

    5     Private Function GetEnumerator() As IEnumerator(Of X) Implements IEnumerable(Of X).GetEnumerator

    6         Return DirectCast(_items.GetEnumerator, IEnumerator(Of X))  'Throws InvalidCastException

    7     End Function

    8 

    9     Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator

   10         Return _items.GetEnumerator

   11     End Function

   12 

   13     Private _items() As X

   14 

   15 End Class

   16 

Line 6 throws an exception with the message "Unable to cast object of type 'SZArrayEnumerator' to type 'System.Collections.Generic.IEnumerator`1[System.Int32]'."

The answer is simple, but had me scratching my head for a while:

    6 Return DirectCast(_items, IEnumerable(Of X)).GetEnumerator

3 comments:

Boinst said...

Thankyou! Saved my life.

Anonymous said...

Thanks a lot, saved me from eons of forum browsing and questions.

Anonymous said...

Thanks a lot, saved me from eons of pointless forum browsing and questions. I had the same problem in C#, and same solution worked. In C# it's "((IEnumerable)this.arr).GetEnumerator()"