title: Setting parameter to DBNull.Value using ternary syntax gives error?
body: <p>I have the following bit of code to set a parameter that will be used in an INSERT statement to set a VARCHAR column in a SQL Server database.  My value object (named ilo) has a property called Description that gets initialized to String.Empty, and then either gets set to some value read from XML, or if that XML element is empty it just stays as String.Empty.</p>
  <p>So when inserting into the database, if the property is still set to String.Empty, I'd like to have it insert a null value.</p>
  <pre><code>database.AddInParameter(cmd, &quot;@description&quot;, DbType.String, 
                             (ilo.Description.Equals(string.Empty)) ?
                              DBNull.Value :
                              ilo.Description);
  </code></pre>
  <p>So basically I'm saying, if ilo.Description equals string.empty, set the parameter to DBNull.Value, otherwise set it to ilo.Description.</p>
  <p>This gives the following error in Visual Studio...</p>
  <p>Error   141 Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'string'</p>
  <p>Why?</p>
  <p>The curious part is that I can do the following with no error, which should be exactly the same thing as using inline conditional syntax like above!?!</p>
  <pre><code>if(ilo.Description.Equals(string.Empty))
  {
      database.AddInParameter(cmd, &quot;@description&quot;, DbType.String, DBNull.Value);
  }
  else
  {
      database.AddInParameter(cmd, &quot;@description&quot;, DbType.String, ilo.Description);
  }
  </code></pre>
  <p>I searched other posts, and found the one below, but it doesn't really answer my question.</p>
  <p><a href="https://stackoverflow.com/questions/1252677/entlib-way-to-bind-null-value-to-parameter">EntLib Way to Bind &quot;Null&quot; Value to Parameter</a></p>
  <p>I'm more interested in WHY, because the obvious workaround is to just use an if/else statement instead of the inline (ternary) syntax?</p>
  <p>There's sort of an answer at this link, but I'd like a better explanation because it seems to be BS to me that this doesn't work; I'd call it a bug!</p>
  <p><a href="http://msdn.microsoft.com/en-us/library/ty67wk28.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ty67wk28.aspx</a></p>
  <p>EDIT: 3/30/2021, it's been 9 years since I wrote this question.  Finally as of C# 9, this issue is fixed.  Ternary expressions now support mixed types so long as they can be implicitly converted.</p>