views:

354

answers:

2

Hi,

I have a resultset class:

Public Class AResultSet
    Implements IEnumerable(Of ConcreteResult)

    Private _list As List(Of ConcreteResult)

    Public Sub New()
        _list = New List(Of ConcreteResult)
    End Sub

    Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of ConcreteResult) Implements System.Collections.Generic.IEnumerable(Of ConcreteResult).GetEnumerator
        Return _list.GetEnumerator
    End Function

    Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
        Return _list.GetEnumerator
    End Function
End Class

and a linq query:

Dim res As AResultSet = (From pk In testPackages, _
         pp In pk.PackagePriceCollection _
          Select New ConcreteResult(pk, pp))

But I get a cast error. So if I change the

Dim res As AResultSet

To:

Dim res As IEnumerable(Of ConcreteResult)

It works. But I want to cast the linq query result to the type AResultSet, which is also an IEnumerable(Of ConrecteResult).

Or am I doing something wrong here?

+3  A: 

The result of calling Select is not an AResultSet, which is why the cast will fail. Nothing in the query knows that you want to create a AResultSet. Just because the result and AResultSet both implement the same interface doesn't mean they're the same type.

You could create an instance of AResultSet from the results, however:

Dim query = (From pk In testPackages, _
     pp In pk.PackagePriceCollection _
     Select New ConcreteResult(pk, pp))
Dim res as AResultSet = new AResultSet(query.ToList)
Jon Skeet
A: 

While it's unclear to me why you might want to create a class to duplicate the functionality of List(Of T), what you are trying to do is not directly possible. You should either create an implicit (Widening) user defined cast operator in your class or create a constructor that takes an IEnumerable(Of ConcreteResult) and uses that to fill the private list field.

Public Class AResultSet
      Implements IEnumerable(Of ConcreteResult)
   Private list As List(Of ConcreteResult)
   Private Sub New(l As List(Of ConcreteResult))
      list = l
   End Sub
   Public Shared Widening Operator CType(seq As IEnumerable(Of ConcreteResult)) As AResultSet
      Return New AResultset(seq.ToList())
   End Sub
   ...
End Class
Mehrdad Afshari