Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this typecast cause an error?

Tags:

c#

.net

casting

This works as expected:

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

While this throws an InvalidCastException:

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

Why does the cast fail from an object when the underlying type is still byte?

like image 800
Jeremy Elbourn Avatar asked Oct 28 '11 14:10

Jeremy Elbourn


People also ask

What is typecast error?

Above code type casting object of a Derived class into Base class and it will throw ClassCastExcepiton if b is not an object of the Derived class. If Base and Derived class are not related to each other and doesn't part of the same type hierarchy, the cast will throw compile time error.

Why do we typecast in Java?

Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.

What is an example of typecasting?

An example of typecasting is converting an integer to a string. This might be done in order to compare two numbers, when one number is saved as a string and the other is an integer. For example, a mail program might compare the first part of a street address with an integer.

What does it mean to cast a variable?

In Java, type casting is used to convert variable values from one type to another. By casting we don't mean something to do with fishing, but it is a similar idea to casting a pot in clay. In Java when you cast you are changing the “shape” (or type) of the variable.


1 Answers

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

If you tell the compiler the object is really a byte, then it will once again allow you to explicitly cast to int.

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

References:

Casting and Type Conversions
byte

like image 177
Jamiec Avatar answered Oct 18 '22 22:10

Jamiec