38653

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

Question:

This question already has an answer here:

<ul><li> <a href="/questions/9436852/possible-to-use-the-coalesce-operator-with-dbnull" dir="ltr" rel="nofollow">Possible to use ?? (the coalesce operator) with DBNull?</a> <span class="question-originals-answer-count"> 6 answers </span> </li> </ul>

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?

<hr />

To be more precise:

Is there a way to get <strong>COALESCE</strong>-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.

<hr />

<strong>SOLUTION</strong>

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

Answer1:

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;

Answer2:

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:<br /> 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 <a href="http://msdn.microsoft.com/en-us/library/scekt9xw.aspx" rel="nofollow">HERE</a>. This should be faster then a value comparisson with DBNull.Value...

Answer3:

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

Answer4:

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"]

Answer5:

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;

Recommend

  • Having difficulty working with global variables and $.getScript
  • How to give photo to dialog from user's blob id?
  • How to return an object in my case?
  • what is the diference between cascading and chaining [closed]
  • Spark dataframes: Extract a column based on the value of another column
  • Changing NULL's position in sorting
  • OpenCL bytecode running on another card
  • How do I conditionally select a field from one of two tables?
  • Django: Serializing a list of multiple, chained models
  • Filtering SPARQL results by day and month
  • SQL Server Integrated Security from an Azure Web Site
  • Using self.id to populate other fields in Django
  • Furthest-point Voronoi diagram in Java
  • Get all existing pointers to an object
  • Hibernate in Glassfish - Ejb3Configuration NoClassDefFoundError
  • Cursor in wrong place in contenteditable
  • Merge Module leaving files during uninstall
  • How do I import an existing Grails 3 (3.0.12) project in IntelliJ 15
  • Spring integration inbound-gateway Fire an event when queue is empty
  • Cloud Code function running twice
  • WPF version of .ScaleControl?
  • Convert SQLite database to XML
  • Redirect STDERR in OPEN pipe comand. Perl Linux
  • WPF Visiblity Binding to Boolean Expression with multiple Variables
  • Z3: Convert between FP and BitVector?
  • Conversion from string “a” to type 'Boolean' is not valid
  • Django rest serializer Breaks when data exists
  • How to rebase a series of branches?
  • How can I send an e-mail from a vbs script
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Azure Cloud Service Web Role web pages do not load
  • Can Jackson SerializationFeature be overridden per field or class?
  • Convert array of 8 bytes to signed long in C++
  • what is the difference between the asp.net mvc application and asp.net web application
  • Arrays break string types in Julia
  • Understanding cpu registers
  • how does django model after text[] in postgresql [duplicate]
  • How to get Windows thread pool to call class member function?
  • Recursive/Hierarchical Query Using Postgres
  • Running Map reduces the dimensions of the matrices