Operator '??' cannot be applied to operand

2019-04-18 07:15发布

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?

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-18 07:56

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

查看更多
可以哭但决不认输i
3楼-- · 2019-04-18 08:03

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);
查看更多
姐就是有狂的资本
4楼-- · 2019-04-18 08:04

Both operands need to be object. Use explicit cast:

(object)table.Value ?? DBNull.Value;
查看更多
爷、活的狠高调
5楼-- · 2019-04-18 08:05

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.

查看更多
登录 后发表回答