title: C# ?? operator with DBNull (Coalesce-like result)
body: <p>I'm getting DBNull results from DB. </p>
  
  <p>Trying to apply ?? operator to it like</p>
  
  <pre><code>result["field1"] ?? result["field2"]
  </code></pre>
  
  <p>field1 = DBNull</p>
  
  <p>field2 = 4</p>
  
  <p>but it doesn't work, returns {} because result["field1"] is not null (it's DBNull). I expect to get that 4 from it.</p>
  
  <p>Tried to do</p>
  
  <pre><code>result["field1"] = null
  </code></pre>
  
  <p>first, but it doesn't work, it's still DBNull type. </p>
  
  <p>The question is how to handle this, convert DBNull to null in some way?
  How to make ?? operator work with DBNull values?</p>
  
  <hr>
  
  <p>To be more precise:</p>
  
  <p>Is there a way to get <strong>COALESCE</strong>-like behaviour?</p>
  
  <p>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...)</p>
  
  <p>I wasn't precise with that, sorry, my fault.</p>
  
  <hr>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>Following Peter van der Heijden solution, say I'm getting from DB</p>
  
  <p>result["field1"] = DBNull</p>
  
  <p>result["field2"]= DBNull</p>
  
  <p>result["field3"] = 4</p>
  
  <pre><code>result["field1"] ?? result["field2"] ?? result["field3"]
  </code></pre>
  
  <p>will return {} (first not null, DBNull is ... well ... not null)</p>
  
  <p>but </p>
  
  <pre><code>result["field1"] as int? ?? result["field2"] as int? ?? result["field3"] as int?
  </code></pre>
  
  <p>will return result["field3"] = 4, as expected.</p>
  
  <p>int? can be replaced with whatever result type you get (like DateTime? for example).</p>