Reputation: 37212
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)
Upvotes: 1
Views: 1036
Reputation: 1502825
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).
Upvotes: 5