Cast of a Generic Type in .NET -
why following cast not working ?
public void add<t>() t : myinterface {    var newobject = new factory<t>() factory<myinterface>;     ... }  public class factory<t> t : myinterface  { ... } newobjects remains null.
probably because factory<t> not subtype of factory<myinterface>, , cast fails.
factory<t> invariant (assuming it's class), means factory<string> not derive factory<object>, though string derives object.
what you're looking covariance. unfortunately, classes cannot variant in c#, interfaces can, iiiif generic type parameter t used output (e.g., method's return type) , never input (e.g., method parameters).
if factory uses t output, can define covariant inteface such as:
public interface ifactory<out t> {}  public class factory<t> : ifactory<t> {} now can cast ifactory<t> t:myinterface ifactory<myinterface>
Comments
Post a Comment