By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,346 Members | 2,318 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,346 IT Pros & Developers. It's quick & easy.

Generic casting problem ?

P: n/a
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.

Mar 20 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"Herby" <pr********@gmail.com> wrote in message
news:11**********************@g10g2000cwb.googlegr oups.com...
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.


Thanks.

Mar 23 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.