C # error explanation for int or object-to-double

For the last assignment, the code below:

static void Main(string[] args) { int a = 5; object b = 5; System.Diagnostics.Debug.Assert( a is int && b is int ); double x = (double)a; double y = (double)b; } 

If both a and b are int , what is the cause of this error?

+6
source share
4 answers

This is a very frequently asked question. See http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx for an explanation.


Excerpt:

I get quite a few questions about the C # lithium operator. The most common question I get is:

 short sss = 123; object ooo = sss; // Box the short. int iii = (int) sss; // Perfectly legal. int jjj = (int) (short) ooo; // Perfectly legal int kkk = (int) ooo; // Invalid cast exception?! Why? 

Why? Because in box T you can only unzip to T (*) After it is unpacked, it is just a value that can be executed as usual, so double-clicking works fine.

(*) Or Nullable<T> .

+20
source

Unboxing requires the exact type - you can do this instead:

 double y = (double)(int)b; 
+15
source

Implicit casting is a compile-time operation. This is not possible for b type object .

+1
source

a is int , but b is a reference to an object that is int - this is what is called a boxed int. These are two different things, hence different types of behavior.

0
source

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


All Articles