Typecasting of generic type

Typecasting of generic type

am 15.10.2007 17:40:27 von 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

Re: Typecasting of generic type

am 15.10.2007 18:51:52 von skeet

wrote:
> 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.

--
Jon Skeet -
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too