InvalidCastException

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I was debugging an error in a C# application (.NET framework 1.1) and I found
out a behaviour that I'm not able to understand.
In the following code snippets I report 3 cast situations.
Could anybody explain me what's going on in case 3 ?

---- case 1 ---
Byte k = (Byte)18;
Int16 m = (Int16)k; // it works OK !!

---- case 2 ---
Byte i1 = (Byte)18;
Object o1 = i1;
Byte j1 = (Byte)o1; // it works OK !!

---- case 3 ---
Byte i2 = (Byte)18;
Object o2 = i2;
Int16 j2 = (Int16)o2; // InvalidCastException is thrown !!!

Thank you very much
Luigi
 
Hi Luigi,

You need to cast it to byte before casting it to int.

Int16 j2 = (Int16)((Byte)o2);
 
Luigi said:
I was debugging an error in a C# application (.NET framework 1.1) and I found
out a behaviour that I'm not able to understand.
In the following code snippets I report 3 cast situations.
Could anybody explain me what's going on in case 3 ?

---- case 1 ---
Byte k = (Byte)18;
Int16 m = (Int16)k; // it works OK !!

---- case 2 ---
Byte i1 = (Byte)18;
Object o1 = i1;
Byte j1 = (Byte)o1; // it works OK !!

---- case 3 ---
Byte i2 = (Byte)18;
Object o2 = i2;
Int16 j2 = (Int16)o2; // InvalidCastException is thrown !!!

When you unbox - which is what you're doing in the third example - you
need to unbox with the exact type which was boxed. You can then cast
the result. So,

Int16 j2 = (Int16)(Byte)o2;

should work fine.

You don't actually need the cast to Int16 at all as there's an implicit
conversion from Byte to Int16, so you can just use

Int16 j2 = (Byte)o2;
 
Back
Top