c# - Generics with inheritance and interfaces - why doesn't this work? -


here's entire application. me, should compile fine.

namespace sampleapp {     interface i<t> t : image     {     }      class a<t> t : image     {     }      class b : a<bitmap>, i<bitmap>     {     }      class c : a<metafile>, i<metafile>     {     }      class program     {         public static i<image> someproperty { get; set; }          static void main(string[] args)         {             b b = new b();                         someproperty = b;              c c = new c();             someproperty = c;         }     } } 

however, lines "someproperty = b" , "someproperty = c" give error:

cannot implicitly convert type 'b' 'i<system.drawing.image>'. explicit conversion exists (are missing cast?) 

but can't work out why. b implements i<bitmap>, , bitmap subclass of image, surely, definition, b implements i<image>.

as sasha says, you're looking generic covariance. may or may not appropriate depending on interface members like. if ever take values "out" of interface, can make code compile making t covariant:

interface i<out t> t : image { } 

however, if have methods accepting t, e.g.

void replacewith(t newimage) 

then can't make t covariant.

generic variance complicated topic - gave talk @ ndc 2010 may find useful. can watch @ ndc video site. search "variance" find quickly. (the real content starts @ 2 minutes.)


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -