title: C# ADO.NET: nulls and DbNull -- is there more efficient syntax?
body: <p>I've got a <code>DateTime?</code> that I'm trying to insert into a field using a <code>DbParameter</code>. I'm creating the parameter like so:</p>
  
  <pre><code>DbParameter datePrm = updateStmt.CreateParameter();
  datePrm.ParameterName = "@change_date";
  </code></pre>
  
  <p>And then I want to put the value of the <code>DateTime?</code> into the <code>dataPrm.Value</code> while accounting for <code>null</code>s.</p>
  
  <p>I thought initially I'd be clever:</p>
  
  <pre><code>datePrm.Value = nullableDate ?? DBNull.Value;
  </code></pre>
  
  <p>but that fails with the error</p>
  
  <blockquote>
    <p>Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'</p>
  </blockquote>
  
  <p>So I guess that only works if the second argument is a non-nullable version of the first argument. So then I went for:</p>
  
  <pre><code>datePrm.Value = nullableDate.HasValue ? nullableDate.Value : DBNull.Value;
  </code></pre>
  
  <p>but that doesn't work either:</p>
  
  <blockquote>
    <p>Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'</p>
  </blockquote>
  
  <p>But I don't want to convert between those types!</p>
  
  <p>So far the only thing I can get to work is:</p>
  
  <pre><code>if (nullableDate.HasValue)
    datePrm.Value = nullableDate.Value;
  else
    datePrm.Value = DBNull.Value;
  </code></pre>
  
  <p>Is that really the only way I can write this? Is there a way to get a one-liner using the ternary operator to work?</p>
  
  <p><strong>Update:</strong> I don't really get why the ?? version doesn't work. MSDN says:</p>
  
  <blockquote>
    <p>The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.</p>
  </blockquote>
  
  <p>That's exactly what I want!</p>
  
  <p><strong>Update2:</strong> Well it was kind of obvious in the end:</p>
  
  <pre><code>datePrm.Value = nullableDate ?? (object)DBNull.Value;
  </code></pre>