.net - Generic abstract argument for method C# -


i have code example. , don't why not compile. not allow convert d a<b>.

d inherits a<c>. c inherits b, mean should able pass d a<b> method argument right? i'm missing obvious here.

using system.collections.generic;  public class program {     public void main()     {         var d = new d();         foo(d);  //cannot convert d a<b>      }      private void foo(a<b> bar)     {      }    }  public abstract class a<typeb> typeb : b {      public abstract list<typeb> list { get; set; }  }  public abstract class b { }  public class c : b {  }  public class d : a<c> {      public override list<c> list { get; set; } } 

this question has been asked hundreds of times on site.

suppose have bowl of fruit. bowl of apples? apple fruit, why bowl of fruit not bowl of apples? because bowl of fruit contain banana, , not bowl of apples.

suppose have bowl of apples. bowl of fruit? want "an apple fruit, therefore bowl of apples bowl of fruit". wrong. a bowl of fruit can put banana into, , since there operation can perform on bowl of fruit cannot perform on bowl of apples, bowl of apples cannot used in context bowl of fruit expected.

the technical name kind of conversion want "generic covariant conversion". c# supports generic covariant conversions in few specific cases:

  • the "outer" type must interface or delegate, example, ienumerable<t>.
  • the "inner" type must reference type, string, not value type, int.
  • the "outer" type must marked safe covariance; checked compiler.

you can use ienumerable<apple> in context ienumerable<fruit> expected because there no way put banana ienumerable<fruit>. cannot use class a<apple> a<fruit> because compiler not convinced have prevented possibility of type banana extends fruit being used in method can accept apple.

do search on site "covariance , contravariance" , find plenty of questions this.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -