c# - Polymorphism in generic type parameters -


i trying use polymorphism in generic type parameters in c#. have reviewed several other questions on (1, 2, 3, 4, 5, 6), i'm still not clear why doesn't work (or if it's allowed).

background

i have following classes:

public class base { }  public class derived<t> : base { }  public class foo { } 

and instance of derived generic type:

var derived = new derived<foo>(); 

the basics

the following statements true:

derived object  derived base  derived derived<foo> 

the problem

when try use derived class type parameter in generic type unexpected behavior. given following lazy instance:

var lazy = new lazy<derived<foo>>(); 

the following true:

lazy lazy<derived<foo>> 

but these false when expected them true:

lazy lazy<object>  lazy lazy<base> 

why this? should true or have misunderstood how generics work?

yes, misunderstood how generic works. biggest limitation usage of generic types (in fact should avoid them as possible because of that). if derived inherits base not true generic<derived> generic<base>. exception covariance , contravariance. if define generic class like:

public class generic<out t> {} 

then generic<derived> generic<base>

if define generic class like:

public class generic<in t> {} 

then generic<base> generic<derived> (surprise, huh?).

why simple cast not work? imagine our generic class looks follows:

public class generic<t>  {     public void func1(t input);     public t func2(); } 

imagine have generic<derived> object , using generic<base>. in case func2 works - returns derived object can caster base. func1 won't work - have function accepts base object actual object has func1 accepts derived objects , not base objects derived, right?

this example explains why in , out inheritance works. if apply in constraint on type parameter in generic class commit t type may returned properties or functions, may never accepted parameter. in such case our generic class looks this:

public class generic<out t>  {     public t func2(); } 

as exaplained in func2 work fine if use generic<derived> object generic<base>. same reason class:

public class generic<in t>  {     public void func1(t input); } 

func1 work fine if object generic<base> used generic<derived> - in case pass func1 derived objects parameters , dervied base definition.


Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -