0

I try to cast from Object type to decimal:

 Object obj = new Object();
 obj = 10;
 decimal dec = (decimal)obj;

but in this row decimal dec = (decimal)obj , I get this Exception:

Specified cast is not valid.

Any idea why this unboxing can't be implemented?

Thank you in advance.

Michael
  • 13,950
  • 57
  • 145
  • 288

3 Answers3

3

which is why you have Convert.ToDecimal() boxing and unboxing can only happen between same types.

10 literal is represented in C# compiler as an System.Int32(correct me if I am wrong people) and hence unboxing of this to a decimal will result in error

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
2

You can only unbox a value type to its original type or the nullable equivalent version of that type.

For the reason behind this read this Eric Lippert's

Ehsan
  • 31,833
  • 6
  • 56
  • 65
2

When you write obj = 10;, object has value of type int.

Try this:

Object obj = new Object();
obj = 10M;
decimal dec = (decimal)obj;

or this:

Object obj = new Object();
obj = 10;
decimal dec = (decimal)(int)obj;

You should read Boxing and Unboxing article on msdn.

For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

kmatyaszek
  • 19,016
  • 9
  • 60
  • 65