Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why downcast fails at runtime

Tags:

c#

casting

I want to know why below downcast fails @ run time:

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 the cases the type of y is System.Double, still why downcst fails in first case?

like image 952
Wondering Avatar asked Dec 08 '25 10:12

Wondering


1 Answers

In the first example; unboxing (what you show) is different to downcasting or conversion; it is perhaps unfortunate that C# uses the same syntax for all 3.

You must unbox value-types (such as int/double) correctly. Or use Convert.ToInt32(y) which has the logic for this embedded.

In the second example, this is a conversion (not an unbox, and not a downcast). Conversions are defined either in the language spec (like in this case) or via custom static operators.

The difference is object. The box changes everything.

like image 118
Marc Gravell Avatar answered Dec 09 '25 23:12

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!