3

Possible Duplicate:
Why can't I unbox an int as a decimal?

Okay, C#/.NET gurus, can someone tell me why this cast works:

static void Main(string[] args)
{
    int _int = 0;
    decimal _decimal = 1;

    _int = (int)_decimal;

    Console.ReadLine();
}

...but neither of these do?

static void Main(string[] args)
{
    int _int = 0;
    decimal d = 1;
    object _decimal = d;

    _int = (int)_decimal;

    Console.ReadLine();
}

static void Main(string[] args)
{
    int _int = 0;
    object _decimal = 1M;

    _int = (int)_decimal;

    Console.ReadLine();
}

I can cast a decimal to an int so long as what I am casting from is an explicitly-declared decimal type, but I can't cast a decimal to an int when the decimal is stored in an object type? What's up with that?

NOTE: I know I can probably use Convert.ToInt32(), but I am trying to figure out this this here is not working.

Community
  • 1
  • 1
oscilatingcretin
  • 10,457
  • 39
  • 119
  • 206
  • 1
    You can also do it in two steps: "_int = (int) (decimal) _decimal". – Joe Jun 10 '11 at 13:39
  • The answer to this seems to be under one of the related links: [Why can't I unbox an int as a decimal?](http://stackoverflow.com/questions/1085097/why-cant-i-unbox-an-int-as-a-decimal) – RickL Jun 10 '11 at 13:39

1 Answers1

1

Because there is an explicit conversion defined in the framework from decimal to int. Read this MSDN documentation.

Steve B
  • 36,818
  • 21
  • 101
  • 174
  • This answer is just plain wrong. The fact that an explicit conversion exists, does not in any way explain why when _unboxing_ the value, no conversion is allowed. On the other hand, the duplicate of this question has an accepted answer that explains exactly what the problem is. – Peter Duniho Feb 16 '21 at 01:38