Why downcast doesn't work at runtime

I want to know why below downcast fails @ runtime:

case 1:

Object y = 10.23;
Console.WriteLine(y.GetType()); //System.Double
int z = (int)y;// fails @ runtime
Console.ReadKey();

case 2:

Double y = 10.23;
Console.WriteLine(y.GetType());//System.Double
int z = (int)y;//success
Console.ReadKey();

In both cases, the type y is System.Double, but why does downcst not work in the first case?

+3
source share
1 answer

In the first example; unboxing (that you show) is different from the slide or conversion; perhaps unfortunately C # uses the same syntax for all 3.

You must correctly remove value types (e.g. int / double). Or use Convert.ToInt32(y)one that has logic for this inline.

( unbox, downcast). (, ), .

- object. .

+11

All Articles