c# - Covariance and Contravariance conversion fails -
i know i'm missing something, shouldn't work!?
public interface ifoo<out ta, in tb> ta : class tb : class { } public class foo<t> : ifoo<t, t> t : class { } public class whatever { } ...
foo<whatever> _foo = new foo<whatever>(); // (changed "foo" "_foo more clear) var f = (ifoo<object, object>)_foo; // cast error fyi: original project .net 4.0 using vs 2013.
edit: appears 'in' type 'tb' parameter (contravariance) must either same type, or derived type. since 'object' supertype (as in, 'object' not derive type 'whatever'), conversion fails. (thanks aasmund eldhuset)
this work:
public class whateverb : whatever { } var f = (ifoo<object, whateverb>)foo; // yay ;)
a foo<string> not ifoo<object, object>, because generic type parameter tb doesn't match - in generic type parameter, actual type must equal or superclass of generic type parameter, string not superclass of object.
the reason cast accepted compiler cast interface type almost always legal (except in corner case petseral mentions), because subclass of type you're casting implements interface.
Comments
Post a Comment