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

主宰稳场 提交于 2019-12-22 01:26:38

问题


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?


回答1:


Both operands need to be object. Use explicit cast:

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



回答2:


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);



回答3:


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




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/4153009/operator-cannot-be-applied-to-operands-of-type-string-and-system-dbnull

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!