c# - Cast MyClass<string> to MyClass<object> fails in runtime -


in developing class should handle various generic lambda expressions, fell rather familiar hole: had myclass<t> class, , tried cast myclass<string> myclass<object>, so:

myclass<string> myclassstring = getmyclass(); // returns myclass<string> myclass<object> myclassobject = myclassstring; 

doing returned compilation error saying there there's no implicit conversion between 2 types, explicit conversion exist. added explicit conversion:

myclass<object> myclassobject = (myclass<object>)myclassstring; 

now code compiled, failed in runtime, claiming conversion illegal.

i using visual studio 2012, , code part of portable class library project compiled c# 5.

just make sure, replaced myclass ilist - same behavior appeared - explicit conversion allowed, fails during run-time.

why? why compiler accept this? what's point of explicit conversion if fails in runtime?

in order allow cast, need mark covariant. however, covariance allowed interfaces (and delegates). like:

interface myinterface<out t> ... 

the reason why can compile explicit cast compiler assumes return value of getmyclass() myclass<object>. that's hard without declaration.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -