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

5

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?

Signalment answered 11/11, 2010 at 9:37 Comment(1)
Maybe because the ?? operator expects to have the same type in each side?Baldheaded
M
54

Both operands need to be object. Use explicit cast:

(object)table.Value ?? DBNull.Value;
Miley answered 11/11, 2010 at 9:39 Comment(3)
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.Apogamy
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.Apogamy
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.Incontrollable
A
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);
Anomaly answered 11/11, 2010 at 9:40 Comment(0)
S
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.

Sonnie answered 20/8, 2018 at 18:31 Comment(0)
A
8

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

Apogamy answered 11/11, 2010 at 9:38 Comment(0)
B
4

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

Biphenyl answered 29/10, 2019 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.