Trying to throw in the box int by byte

Code for illustration:

int i = 5; object obj = i; byte b = (byte)obj; // X 

When starting, a System.InvalidCastException exception is thrown ("The specified cast is invalid") in the string "X". Double-disc work:

  byte b = (byte)(int)obj; 

I would think that you should be able to insert a byte int (if it has a value in the range 0..255) in a byte. Can anyone shed some light on this?

(This is in .net 2.0, if that matters).

+7
casting c #
source share
2 answers

The difference in behavior that you see is the difference between identification and presentation .

Unboxing is an identity listing and a save operation as. However, converting int to byte is a change in representation (since there is a potential loss of precision).

You get an InvalidCastException when you try to unpack an int as a byte , because the identifier of the nested value is not a byte , it is an int . When you write byte b = (byte)obj , you tell the runtime, I know that there is a byte , but that What you really want to say, I think that what can be converted to byte .

To make the last statement, you first need to declare the identifier of the object, which is int . Then and only then can you do a transformation that changes the view in byte .

Please note that this applies even if the target type is β€œlarger”, i.e. Int64 . All explicit conversions for which the destination type is not in the source type inheritance tree are considered changing views. And since all types are derived from System.Object , unboxing by definition cannot change the view.

+18
source share

MSDN explicitly says that unboxing for another type will throw an InvalidCastException .

My understanding is that the type in which the variable is unpacked is actually a parameter of the basic CIL build command . This is the unbox that actually throws an InvalidCastException .

An InvalidCastException is thrown if the object does not fit as valType.

+5
source share

All Articles