This doesn’t seem to work. Is it possible?
public interface IInterface1 {}
public interface IInterface2 { }
public interface IMyT1 : IInterface1 {}
public interface IMyT2 : IInterface2 {}
public abstract class BaseClass<T1, T2> : Interface2 where T1 : IInterface1, where T2 : IInterface2
{
protected T1 T1Obj {get;set;}
public static explicit operator T1(BaseClass<T1,T2> val)
{
return val.T1Obj;
}
}
public class SomeClass : BaseClass<IMyT1, IMyT2>, ISomeClass {}
Any casts to SomeClass fail with an InvalidCastException.
ISomeClass mySomeClass = new SomeClass();
var myT1 = (IMyT1)mySomeClass; //Boom!
It may be crazy but is it possible?
What you’re looking for is generic variance. At least, I assume so – your example code is missing bits that we’d require in order to check that it would actually work.
You can’t use it at all in C# 3 and earlier. In C# 4 you can use it for interfaces and delegates, but only where explicitly marked using
inandoutappropriately on the type parameters – the compiler makes sure it’s all safe, basically.If you search for generic variance or covariance and contravariance on this site, you’ll find plenty of information. Or you could look at Eric Lippert’s blog series on it. I give details of it in chapter 13 of C# in Depth and if you search for "covariance" on the NDC 2010 streaming video site you can stream or download an hour-long talk I gave on the topic.