Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 682
hwcverwe Avatar asked Nov 11 '10 09:11

hwcverwe


5 Answers

Both operands need to be object. Use explicit cast:

(object)table.Value ?? DBNull.Value;
like image 65
Pavel Urbančík Avatar answered Nov 20 '22 18:11

Pavel Urbančík


There is no automatic conversion between string and System.DBNull and so you need to specify the type you want explicitly by adding a cast to object:

sqlCommandObject.Parameters.AddWithValue("@Parameter",
                                         table.Value ?? (object)DBNull.Value);
like image 42
Mark Byers Avatar answered Nov 20 '22 19:11

Mark Byers


Instead of using DBNull.Value, you can use Convert.DBNull:

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

I believe behind the scenes it is basically doing the same/similar thing as mentioned in other examples (i.e. casting DBNull to object), but it makes it a little simpler/conciser.

like image 15
Hutch Avatar answered Nov 20 '22 17:11

Hutch


It's because there is no implicit conversion between string and System.DBNull.

like image 8
Andrew Barrett Avatar answered Nov 20 '22 19:11

Andrew Barrett


Another workaround is to utilize SqlString.Null.

ex: command.Parameters.Add(new SqlParameter("@parameter", parameter ?? SqlString.Null));

Each type has its own version. SqlGuid.Null, SqlDateTime.Null, etc

like image 2
ScubaSteve Avatar answered Nov 20 '22 18:11

ScubaSteve