Operator '??' cannot be applied to operands of type 'string' and 'System.DBNull'

hwcverwe picture hwcverwe · Nov 11, 2010 · Viewed 15.3k times · Source

I have the following C# code:

sqlCommand.Parameters.AddWithValue("@Parameter", table.Value ?? DBNull.Value);

But it throws the following compilation error:

Operator ?? cannot be applied to operands of type string and System.DBNull

Why doesn't the compiler allow this syntax?

Answer

Pavel Urbančík picture Pavel Urbančík · Nov 11, 2010

Both operands need to be object. Use explicit cast:

(object)table.Value ?? DBNull.Value;