c# - How to upcast generic type parameters -


when use reflection in case, created type can many generic types.

basestephandler<basestepdatamodel> activator = (basestephandler<basestepdatamodel>)activator.createinstance(....); 

the created instance can childs of basestepdatamodel.

basestephandler<onedatamodel>
or
basestephandler<twodatamodel>

onedatamodel , twodatamodel extending basestepdatamodel.

this exception get:

unable cast object of type '....globalonboardingsteponehandler' type '....basestephandler`1[....basestepdatamodel]'.

this declaration if globalonboardingsteponehandler.

public class globalonboardingsteponehandler : basestephandler<globalonboardingsteponedatamodel>{} 

you getting exception because globalonboardingsteponehandler inherits basestephandler<globalonboardingsteponedatamodel>, not basestephandler<basestepdatamodel>. common mistake .net generics. generics not covariant type parameters.

see:

c#: cast generic interface base type

http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx

http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx

http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-two.aspx

http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx

http://blogs.msdn.com/b/ericlippert/archive/2007/10/19/covariance-and-contravariance-in-c-part-three-member-group-conversion-variance.aspx

etc...

the issue you assume because globalonboardingsteponedatamodel inherits basestepdatamodel, globalonboardingsteponehandler inherits basestephandler<basestepdatamodel>. isn't case, , can't cast 1 other.

as example, consider following:

var mylistofstrings = new list<string>();  // logic, should compile (it doesn't): var mylistofobjects = ((list<object>)mylistofstrings);  // if did, possible: mylistofobjects.add(1); // holy cow, added integer list of strings!  world coming to? 

now, confusing recovering java programmers because this possible in java. in java, have type erasure, @ runtime list<string> list<object>, , can cast like, , put want it. because clr uses reified generics, not type erasure, list<string> separate , distinct type list<object> or list<integer>


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -