Generic casting problem ?

  • Thread starter Thread starter Herby
  • Start date Start date
H

Herby

Can generic types be casted?

say Vector<Type^>^ to Vector<CodeType^>^

Where CodeType is a derivative of Type

Is this possible ?

Or is there something quite static about generics?

I would like a pointer to Vector<Type^>^
and then dynamically instantiate it to a derivative of Type ???
i.e

Vector<Type^>^ mArray = gcnew Vector<CodeType^>();

Or am i just expecting too much?

How would i get round this problem?

Thanks.
 
Herby said:
Can generic types be casted?

say Vector<Type^>^ to Vector<CodeType^>^

Where CodeType is a derivative of Type

Is this possible ?

Or is there something quite static about generics?

I would like a pointer to Vector<Type^>^
and then dynamically instantiate it to a derivative of Type ???
i.e

Vector<Type^>^ mArray = gcnew Vector<CodeType^>();

Or am i just expecting too much?

How would i get round this problem?

Basically, this is not at all typesafe. Collections are covariant on get
and contravariant on set. (unless I have my terminology backward).

Imagine the following pseudocode:

function HitMe(Vector<Type^>^ hitArray) {
hitArray.Append(typeof(hitArray));
}
That's legal, typeof(hitArray) is a subtype of Type, and can be added to a
Vector of Type

Vector<Type^>^ mArray = gcnew Vector<CodeType^>();
HitMe(mArray); // uh-oh, now mArray contains typeof(mArray), which is not a
subtype of CodeType.
 
Back
Top