30

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?

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
hwcverwe
  • 5,287
  • 7
  • 35
  • 63

5 Answers5

52

Both operands need to be object. Use explicit cast:

(object)table.Value ?? DBNull.Value;
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Pavel Urbančík
  • 1,466
  • 9
  • 6
  • 11
    This isn't really correct, the reason that the compile error happens isn't because both operands to ?? need to be objects. It's that without an explicit cast (provided in the answer with (object)) there needs to be an implicit cast available. As there isn't an implicit cast between string and System.DBNull, you get the compiler error. – Andrew Barrett Nov 11 '10 at 10:17
  • 5
    Not trying to be picky, just worried that the author (who said he knew how to get round the error) might go away thinking that both operands to the ?? operator always need to be objects. His question was *why* does the compiler not like this not *how* do I fix it. – Andrew Barrett Nov 11 '10 at 10:32
  • It might be worth performing the cast on `DBNull.Value` instead. i.e. `table.Value ?? (object)DBNull.Value;` Still helps the compiler to get the idea about what is needed and this way a conversion only happens if the intended value is null. – Menol Nov 08 '19 at 09:08
19

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);
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
15

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.

Hutch
  • 987
  • 10
  • 19
8

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

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Andrew Barrett
  • 19,721
  • 4
  • 47
  • 52
3

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

ScubaSteve
  • 7,724
  • 8
  • 52
  • 65