C# ?? operator with DBNull (Coalesce-like result) [duplicate]

不想你离开。 提交于 2019-12-25 04:19:42

问题


I'm getting DBNull results from DB.

Trying to apply ?? operator to it like

result["field1"] ?? result["field2"]

field1 = DBNull

field2 = 4

but it doesn't work, returns {} because result["field1"] is not null (it's DBNull). I expect to get that 4 from it.

Tried to do

result["field1"] = null

first, but it doesn't work, it's still DBNull type.

The question is how to handle this, convert DBNull to null in some way? How to make ?? operator work with DBNull values?


To be more precise:

Is there a way to get COALESCE-like behaviour?

That 2 fields are just for example, in reality there will be much more fields and I'm trying to get first not null (so I was hoping to use chaining field1 ?? field2 ?? field3...)

I wasn't precise with that, sorry, my fault.


SOLUTION

Following Peter van der Heijden solution, say I'm getting from DB

result["field1"] = DBNull

result["field2"]= DBNull

result["field3"] = 4

result["field1"] ?? result["field2"] ?? result["field3"]

will return {} (first not null, DBNull is ... well ... not null)

but

result["field1"] as int? ?? result["field2"] as int? ?? result["field3"] as int?

will return result["field3"] = 4, as expected.

int? can be replaced with whatever result type you get (like DateTime? for example).


回答1:


I tend to do that as follows:

string s = result["field1"] as string;

or

int? i = result["field2"] as int?;

Or in your case:

string s = result["field1"] as string ?? result["field2"] as string;



回答2:


You could use the slightly longer variant:

result["field1"] is DBNull ? result["field2"] : result["field1"];

?? does only work if the left operand is null and as DBNull is an instance of a class it is not null.

Side note @Amit:
The is operator does a type check. You can interpret it "as you read it": It checks if the type of result["field1"] is DBNull. See HERE. This should be faster then a value comparisson with DBNull.Value...




回答3:


DBNull.Value.Equals(result["field1"]) ? result["field2"]: result["field1"];



回答4:


The ?? operator will never work with DbNull.Value since it is a instance of DbNull.

Use other checks for this, like:

result["field1"] != DbNull.Value ? result["field1"] : result["field2"]



回答5:


The ?? operator only works will actual null values, DBNull is just a type, and DBNull.Value is just a static value used to signify a null value from the database.

You can't get it to work with ??, all you can do is manually check for result["col"] != DBNull.Value, but then obviously this can be put into a method or an extension method so it reads a little nicer.

The ternary operator is about as close as you are going to get: var val = results["col"] != DBNull.Value ? (int)results["col"] : 0;



来源:https://stackoverflow.com/questions/23336917/c-sharp-operator-with-dbnull-coalesce-like-result

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