Why does this cast result in an error?

This works as expected:

byte b = 7; var i = (int)b; 

So far, this throws an InvalidCastException :

 byte b = 7; object o = b; var i = (int)o; 

Why does casting happen with object when the base type is still byte ?

+6
source share
3 answers

Because byte has an explicit conversion to int , but object does not.

If you tell the compiler that object indeed a byte , then it again allows you to explicitly point to int .

 byte b = 7; object o = b; var i = (int)((byte)o); 

Literature:

Convert castings and types
byte

+6
source

This is caused by the use of CLR boxing and unboxing . Whenever you consider a value type as an object, the CLR automatically binds this value type to you inside the object. However, the CLR only supports unpacking objects in a box into their original value type on MSDN :

Unpacking

Unboxing is an explicit conversion from a type object to a type value, or from an interface type to a value type that implements an interface. The unboxing operation consists of:

  • Checking the instance of the object to make sure that this value is in the box of the given type.

  • Copy a value from an instance to a value type variable.

object o = b; Causes the CLR to create a byte in bytes and stores it in o as an object. var i = (int)o; then tries to unpack the byte byte into int. This throws an exception because the type of box (byte) and value type (int) are different.

+1
source

You must first get the byte from the object before you can convert it to an integer.

Something like that:

 var i = (int)(byte)o; 
0
source

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


All Articles