0

I have code below:

class Program
{
    private static void Main()
    {
        object obj = 1;
        Console.WriteLine(Convert.ToDouble(obj)); // why OK without exception?
        var d = (double) obj; // why exception?
    }
}

The "Convert.ToDouble(obj)" works to convert from int to double, but "var d=(double) obj" will throw exception. Why is such a difference? What's the difference between these 2 types of conversions?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
vik santata
  • 2,989
  • 8
  • 30
  • 52
  • 1
    http://ericlippert.com/2009/03/03/representation-and-identity/ – SLaks Jun 18 '15 at 00:51
  • 2
    Conversion is changing one object to another through rules you define yourself. Casting is pretending an object is of a different type and hoping you can get away with it. It doesn't let you get away with it here. – Jeroen Vannevel Jun 18 '15 at 00:57
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Jun 18 '15 at 01:05

3 Answers3

2

For a cast, the object needs to be the type that it should be casted to. In your example thats an Integer.

A working double cast would be:

object obj = 1d;
var t = (double)obj;
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
Boot750
  • 891
  • 1
  • 7
  • 17
0

You don't have to jump through the multiple cast hoop, simple value types implement the IConvertible interface. Which you invoke by using the Convert class. So basically as your object contains a int value you cannot use the type cast to convert it directly to decimal. But you can still use:

var d = (int)obj

Whereas you can use Convert interface to jump through multiple cast.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Arun Kumar
  • 907
  • 13
  • 33
  • The OP is talking about `double`, not `decimal`. Also, there's no "double cast". There are no casts which can help his situation, and Convert.ToDouble is not using casts. – John Saunders Jun 18 '15 at 01:06
0

Refer this question:
Difference between casting and using the Convert.To() method
@Servy's answer is a good explaination.

Community
  • 1
  • 1
GIANGPZO
  • 380
  • 2
  • 3
  • 21