tags:

views:

106

answers:

3

Hi All, 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:

enter code here    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?

+11  A: 

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.

Marc Gravell
thanks, I got the point.In first case is there ant other way of unboxing rather than Convert.ToInt32(y)
Wondering
Yes - you can do `(int)(double)y`, which unboxes (correctly) to `double`, and *then* does a *conversion* to `int`.
Marc Gravell
yes, worked.so the chain is boxing-->unboxing and that -->conversion.Thanks for ur help.
Wondering
The rules can be summed up thus: 1) source reference type, target reference type - upcast/downcast/interface case; 2) source reference type, target value type - unboxing; 3) source value type, target reference type - boxing; 4) source value type, target value type - conversion. Of those 4, only the last one involves actual widening or narrowing conversions. Of course, this all assumes no overloaded conversion operators, as those can do anything they want.
Pavel Minaev
Good points.it will help in future :-).Thanks.
Wondering
+1  A: 

Marc is of course correct. For a longer analysis of why this sort of cast is not legal, see my article on the subject:

http://blogs.msdn.com/ericlippert/archive/2009/03/19/representation-and-identity.aspx

Eric Lippert
A: 

I found the longer discussion Casting – the escape from strong typing to be useful - but I have to add that casting is very messy and a clean distinction between type and represenation conversion would be a good idea and boxing makes it even worse.