C #: cause of error message for InvalidCastException

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.

+4
source share
2 answers

Well, what else can the message say?

If he said: "It is impossible to impose an object of type" object "is the type of" the Foo ", it will be confusing and less useful because obj is not an instance of the object , and you would not have any way to know that obj is an instance.

Another alternative might be something like the lines “Unable to use an object of type“ Bar ”(link as“ object ”) to type“ Foo ”, but it is verbose and rather confusing. Perhaps this could be formulated better, but still verbose - in addition, you can quickly find the same information just by looking at the source code.

When you think about it, the message is valid (even if it does not tell the whole story). It can be distinguished from Bar to Foo , but in this particular case the CLR was unable to perform this cast.

+2
source

In your code:

 public static explicit operator Foo(Bar bar) { 

This might work:

 public static implicit operator Foo(Bar bar) { 

Or you can write:

 Foo foo = (Foo)(Bar)bar; 
0
source

Source: https://habr.com/ru/post/1347518/


All Articles