Typecasting of generic type

  • Thread starter Thread starter bugmenot
  • Start date Start date
B

bugmenot

I want to cast a generic class into another. Only difference is the
type parameter used. In my original problem it would be an upcast of
the type parameter but even downcasting doesn't seem to work... I
tried the same in C# with the same results. I keep getting '....
cannot convert... ' messages in both languages.
Does anybody know if this is a limitation of the CLR and if there is a
lazy way to overcome this restriction? Or am I simply missing
something?

Thanks,
Thomas

Public Class dummy
Public Class A
End Class

Public Class B
Inherits A
End Class

Public Class C(Of T As A)
End Class

Public Function f() As C(Of A)
Return New C(Of B) ' <-- ERROR
Return CType(New C(Of B), C(Of A)) ' <-- ERROR
End Function
End Class
 
I want to cast a generic class into another. Only difference is the
type parameter used. In my original problem it would be an upcast of
the type parameter but even downcasting doesn't seem to work... I
tried the same in C# with the same results. I keep getting '....
cannot convert... ' messages in both languages.
Does anybody know if this is a limitation of the CLR and if there is a
lazy way to overcome this restriction? Or am I simply missing
something?

What you're after is called variance - and the CLR doesn't support it
in the general case. (It supports it with interfaces in some cases, but
they aren't exposed in C# anyway, and I imagine the same is true for
VB.)

See http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx for
more info.
 
Back
Top