mawera

HI,

can anybody help me understand the reason / workaround for this problem:

Unable to cast object of type 'System.Collections.Generic.List`1[VvDataRecord]' to type 'ListExtended`1[VvDataRecord]'.

where

public class ListExtended<T> : List<T> where T : VvDataRecord
{
SomeExtendingMethod() ...
}

Regards



Re: Visual C# Language Casting List<T> to ListExtended<T>

Greg Beech

It's because generics are not covariant, so if B : A then it does not imply X<B> : X<A>, in fact there is no relationship at all between X<B> and X<A>.

If you're used to arrays, then this may seem odd as B : A implies that B[] : A[].

There is no workaround, per se, except not to put yourself in a situation where one must be cast to another. What problem are you trying to solve specifically We can help you find a way to solve it.





Re: Visual C# Language Casting List<T> to ListExtended<T>

mawera

Hi Greg,

thanks for your reply.

Your point stands but it seems that you misunderstood my problem.

My goal is to establish relationship between X<A> and Y<A> where Y : X

Regards





Re: Visual C# Language Casting List<T> to ListExtended<T>

Greg Beech

Ah, apologies, the other question comes up so often I was almost on auto-pilot. Looking again, it seems you shouldn't have a problem, as if B<> : A<> then B<X> : A<X>

Is it a compile time error or a runtime error you are getting A runtime error would occur if you tried to cast the wrong way, e.g. if you tried to cast an object of concrete type A<X> to B<X> then it would fail as you are casting to a more derived type, however casting an object of concrete type B<X> to A<X> would be fine, as you are casting to a less derived type.

Maybe a small code sample that demonstrates the problem would help us to have a look





Re: Visual C# Language Casting List<T> to ListExtended<T>

mawera

Thanks Greg. You are very kind.

As struggling with Generics I overlooked the fact that I'm casting to more derived type.

Thanks for your time.