From: Peter Duniho on
Jesse Houwing wrote:
> * Fred Chateau wrote, On 13-1-2010 23:30:
>> I can't get the following line of code to work. Any idea how to do this?
>>
>> int? result = subCategoryRow["RevisionNumber"].Equals(DBNull.Value) ?
>> null : (int?) subCategoryRow["RevisionNumber"];
>>
>> I get an invalid cast exception.
>
> Try:
> int? result = subCategoryRow.IsNull("RevisionNumber") ?
> (int?)null : (int) subCategoryRow["RevisionNumber"];
>
> You need to cast the null to Nullable type in order to use it in the ?:
> construction in order for it to work.

That's only true if the other operand has a type other than "int?".

For example, this sample code works fine:

int i1 = 5;

int? i2 = (i1 < 5) ? null : (int?)i1;

Note that the OP is not asking about a compile-time error. He's getting
a run-time InvalidCastException.

The compiler will make an attempt to coerce one operand to the other, in
order to determine the type of the entire expression. The "null" can be
coerced to any other nullable type, so it compiles fine if the other
operand is "int?", as in the OP's original example.

Pete
From: Arne Vajhøj on
On 13-01-2010 17:30, Fred Chateau wrote:
> I can't get the following line of code to work. Any idea how to do this?
>
> int? result = subCategoryRow["RevisionNumber"].Equals(DBNull.Value) ?
> null : (int?) subCategoryRow["RevisionNumber"];
>
> I get an invalid cast exception.

Try print out subCategoryRow["RevisionNumber"].GetType().Name and
see what it actually is.

Arne