Casting with conditional/ternary ("?:") operator

The difference is that the compiler can not determine a data type that is a good match between Object and Int32.

You can explicitly cast the int value to object to get the same data type in the second and third operand so that it compiles, but that of couse means that you are boxing and unboxing the value:

result = (decimal)(valueFromDatabase != DBNull.value ? valueFromDatabase : (object)0);

That will compile, but not run. You have to box a decimal value to unbox as a decimal value:

result = (decimal)(valueFromDatabase != DBNull.value ? valueFromDatabase : (object)0M);

UPDATE: This question was the subject of my blog on May 27th 2010. Thanks for the great question!

There are a great many very confusing answers here. Let me try to precisely answer your question. Let's simplify this down:

object value = whatever;
bool condition = something;
decimal result = (decimal)(condition ? value : 0);

How does the compiler interpret the last line? The problem faced by the compiler is that the type of the conditional expression must be consistent for both branches; the language rules do not allow you to return object on one branch and int on the other. The choices are object and int. Every int is convertible to object but not every object is convertible to int, so the compiler chooses object. Therefore this is the same as

decimal result = (decimal)(condition ? (object)value : (object)0);

Therefore the zero returned is a boxed int.

You then unbox the int to decimal. It is illegal to unbox a boxed int to decimal. For the reasons why, see my blog article on that subject:

Representation and Identity

Basically, your problem is that you're acting as though the cast to decimal were distributed, like this:

decimal result = condition ? (decimal)value : (decimal)0;

But as we've seen, that is not what

decimal result = (decimal)(condition ? value : 0);

means. That means "make both alternatives into objects and then unbox the resulting object".