Search code examples
c#doubleprimitive-typesdbnull

How to assign DBNull to a primitive type to facilitate Database insert


I have the following line in my code assigning a value to a datatable column. It could be null or a price.

double? Price;
price = range.Cells[i, j].Value2 == null ? Double.NaN : range.Cells[i,j].Value2;
row["Price"] = **(price != Double.NaN) ? price.Value** : (object)DBNull.Value;

VS 2010 produces a green squiggly line (the code within the pairs of stars) saying

The expression type is always false since double can never be null

How can I get around this so that I can assign null for price in the database table if need be?


Solution

  • Using Double.NaN won't help you because NaN is not equal even to itself. It's not clear why you're doing this in two stages though - I'd suggest just:

    row["Price"] = range.Cells[i, j].Value2 ?? (object) DBNull.Value;