[Mono-list] Collections of generic objects: IDictionary casting problem
Generic 2006
generic2006 at libero.it
Wed Dec 6 06:56:46 EST 2006
Hi all
I have a problem casting collections of generic objects.
I've implemented two collections using the IDictionary<K,V> generic
interface; the values of these two collections are typed using classes
that have a common generic ancestor (Wrapper<InnerType>). I tried to
cast both of them using such common denominator (Wrapper<InnerType>),
but I got both runtime and compiletime exceptions (see below).
Probably I missed some subtlety of the semantics of generics constructs,
but I'd like your opinion.
Many Thanks!
These are the available classes:
class OuterTypes1 : IDictionary<String,OuterType1>{...}
class OuterType1 : Wrapper<InnerSubType1>{...}
class InnerSubType1 : InnerType{...}
class OuterTypes2 : IDictionary<String,OuterType2>{...}
class OuterType2 : Wrapper<InnerSubType2>{...}
class InnerSubType2 : InnerType{...}
class Wrapper<T> where T : InnerType{...}
class InnerType{...}
This is the inheritance hierarchy:
InnerType
+-InnerSubType1
+-InnerSubType2
Wrapper<InnerType>
+-OuterTypes1
+-OuterTypes2
Here it is a sample excerpt from my code:
{
OuterTypes1 myOuterTypes1;
OuterTypes2 myOuterTypes2;
...
{
IDictionary<String,OuterType1> types;
/*
This assignment works fine.
*/
types = (IDictionary<String,OuterType1>)myOuterTypes1;
}
{
IDictionary<String,Wrapper<InnerType>> types;
/*
The following assignment throws a compile-time exception:
error CS0266: Cannot implicitly convert type
'System.Collections.Generic.IDictionary<System.String,OuterType1>' to
'System.Collections.Generic.IDictionary<System.String,Wrapper<InnerType>>'.
An explicit conversion exists (are you missing a cast?)
but I can't figure out why, as Wrapper<InnerType> should be a super
type of OuterType1 (which extends Wrapper<InnerSubType1>),
as InnerType is a super type of InnerSubType1.
*/
types = (IDictionary<String,OuterType1>)myOuterTypes1;
}
{
IDictionary<String,Wrapper<InnerType>> types;
/*
The following assignment throws a run-time exception:
System.InvalidCastException: Cannot cast from source type to destination
type
but I can't figure out why, as Wrapper<InnerType> should be a super
type of OuterType1 (which extends Wrapper<InnerSubType1>),
as InnerType is a super type of InnerSubType1.
*/
types = (IDictionary<String,Wrapper<InnerType>>)myOuterTypes1;
}
}
More information about the Mono-list
mailing list