Let A
, B : A
, C<T>
, and D : C<B>
be classes. Shouldn't I be able to cast a D
to a C<A>
?
public enum TheEnem
{
One,
Two
}
/// <summary>
/// out means 'contravariant'
/// which means that if U : T then an ITheInterface<U> can be cast to an ITheInterface<T>
/// </summary>
public interface ITheInterface<out T> where T : IComparable
{
T First { get; }
T Second { get; }
}
public class TheClass : ITheInterface<TheEnem>
{
public TheEnem First { get; set; }
public TheEnem Second { get; set; }
public TheClass(TheEnem first, TheEnem second)
{
First = first;
Second = second;
}
}
class Program
{
static void Main(string[] args)
{
// There is no proble casting an enum member to IComparable.
TheEnem e = TheEnem.Two;
IComparable ec = e;
IComparable ecc = (IComparable)e;
TheClass a = new TheClass(TheEnem.One, TheEnem.Two);
// We can cast the outer type OK.
ITheInterface<TheEnem> i = a; // This doesn't need the 'out' -- we're not changing T.
// But not the iner one:
//ITheInterface<IComparable> c = a; // Cannot implicitly convert type TheClass' to 'ITheInterface<System.IComparable>'. An explicit conversion exists (are you missing a cast?)
// So let's cast explicitly:
ITheInterface<IComparable> c = (ITheInterface<IComparable>)a;
// Now we get an excpetion at runtime:
// Unable to cast object of type 'TheClass' to type 'ITheInterface`1[System.IComparable]
}
}