digdig
digdig

Reputation: 240

C# int- or object-to-double casting error explanation

The below code fails at the last assignment:

static void Main(string[] args)
{
    int a = 5;
    object b = 5;

    System.Diagnostics.Debug.Assert( a is int && b is int );

    double x = (double)a;
    double y = (double)b;
}

If both a and b are int, what is the cause of this error?

Upvotes: 12

Views: 7876

Answers (5)

rahicks
rahicks

Reputation: 603

This is one of the rare cases where System.Convert comes in handy. You can use System.Convert.ToDouble(obj) to knock it out if you don't know beforehand that it will be int.

Upvotes: 7

Eric Lippert
Eric Lippert

Reputation: 660058

This is an extremely frequently asked question. See https://ericlippert.com/2009/03/03/representation-and-identity/ for an explanation.


Snippet:

I get a fair number of questions about the C# cast operator. The most frequent question I get is:

short sss = 123;
object ooo = sss;            // Box the short.
int iii = (int) sss;         // Perfectly legal.
int jjj = (int) (short) ooo; // Perfectly legal
int kkk = (int) ooo;         // Invalid cast exception?! Why?

Why? Because a boxed T can only be unboxed to T. (*) Once it is unboxed, it’s just a value that can be cast as usual, so the double cast works just fine.

(*) Or Nullable<T>.

Upvotes: 26

tech-man
tech-man

Reputation: 3246

Implicit casting is a compile-time operation. It's not possible for b of type object.

Upvotes: 3

MiMo
MiMo

Reputation: 11953

a is an int, but b is a reference to an object that is an int - it is what is called a boxed int. They are two different things, hence the different behaviors.

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160892

Unboxing requires the exact type - you can do this instead:

double y = (double)(int)b;

Upvotes: 17

Related Questions