views:

370

answers:

1

Hi,

I have a class SomeClass, which can populate itself from a datarow in it's constructor. This class implements IInterface. However, when I execute the code below:

Dim fpQuery As IEnumerable(Of IInterface) = _
    From dr As DataRow In DataLayer.SomeMethodToGetADataTable.AsEnumerable _
    Select New SomeClass(dr)

I get the error

Unable to cast object of type 
'System.Data.EnumerableRowCollection`1[Classes.SomeClass]' 
to type
'System.Collections.Generic.IEnumerable`1[Interfaces.IInterface]'

I should probably add that the following code works fine.

Dim fpQuery As IEnumerable(Of SomeClass) = _
    From dr As DataRow In DataLayer.SomeMethodToGetADataTable.AsEnumerable _
    Select New SomeClass(dr)

As does the simple cast

Dim myInterface As IInterface = New SomeClass(myDataRow)

Any ideas?

EDIT : Jon Skeet got it spot on. I used the following code and it worked perfectly.

Dim fpQuery2 As IEnumerable(Of IInterface) = fpQuery.Cast(Of IInterface)
+4  A: 

You're running into a lack of variance in generics. To put it in a simpler example, you can't treat IEnumerable(Of String) as IEnumerable(Of Object).

The simplest thing would probably be to add a call to Cast(Of TResult).

Jon Skeet
Many thanks - that was exactly what I was looking for.
RB