In developing a class that should handle various generic lambda expressions, I fell into a rather familiar hole: I had a MyClass<T>
class, and I tried to cast MyClass<string>
to MyClass<object>
, like so:
MyClass<string> myClassString = GetMyClass(); // Returns MyClass<String>
MyClass<object> myClassObject = myClassString;
Doing so returned an compilation error saying there there's no implicit conversion between the two types, but that an explicit conversion does exist. So I added the explicit conversion:
MyClass<object> myClassObject = (MyClass<object>)myClassString;
Now the code compiled, but failed in runtime, claiming the conversion is illegal.
I am using Visual Studio 2012, and the code is part of a Portable Class Library project compiled with C# 5.
Just to make sure, I replaced MyClass
IList
- the same behavior appeared - an explicit conversion is allowed, but fails during run-time.
Why? Why does the compiler accept this? What's the point of the explicit conversion if it fails in runtime?