This particular question is more about trying to see the reason for the compiler message than solving the problem, but I hope everything is fine.
Say we have:
class Foo { public static explicit operator Foo(Bar bar) { return new Foo(); } }
The implementation of Bar not important. Now, when you try to do the following, an exception is thrown:
object obj = new Bar(); Foo foo = (Foo)obj;
It InvalidCastException an InvalidCastException , and that’s right, because we don’t have a cast operator for the object type. But exception message:
System.InvalidCastException: cannot discard an object of type "Bar" to enter "Foo"
Which type is misleading, because I can obviously use an object of type Bar to input Foo . I expect the compiler to tell me that I'm basically trying to create an object of type System.Object , not Bar . Is my understanding wrong, and if so, what is the reason for this behavior?
Thank you in advance
EDIT: just to be clear, I know how to handle the problem, and that Foo foo = (Foo)(Bar)bar will do the trick. I am more curious about this error message itself.
source share