title: Is it safe to always type a DBNull SqlParameter as an int?
body: <p>Recently, we ran into the following issue:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/18170985/null-value-in-a-parameter-varbinary-datatype">Null value in a parameter varbinary datatype</a></li>
  </ul>
  
  <p>In a nutshell: <code>myCommand.Parameters.AddWithValue("@SomeParameter", DBNull.Value);</code> apparently "types" the DBNull parameter as an nvarchar, which can be implicitly converted to <em>almost</em> all other types, but, unfortunately, not <code>varbinary</code>, yielding the following error:</p>
  
  <blockquote>
    <p>Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.</p>
  </blockquote>
  
  <p>Unfortunately, the solutions suggested in the linked question do not apply, since we use <code>AddWithValue</code> deep inside a data access library which is designed to infer the data type from the parameter type and does not support adding the "real" SQL Server type.</p>
  
  <p>I "fixed" this issue by explicitly typing DBNull parameters as <code>int</code>s instead:</p>
  
  <pre><code>void MyImprovedAddWithValue(SqlCommand cmd, string key, object value)
  {
      if (value == DBNull.Value) 
      {
          cmd.Parameters.Add(key, SqlDbType.Int).Value = DBNull.Value;
      }
      else
      {
          cmd.Parameters.AddWithValue(key, value);
      }
  }
  </code></pre>
  
  <p>This <em>seems</em> to work. Apparently, NULL typed as int <em>can</em> be implicitly converted to any other type supported by SQL Server.</p>
  
  <p>Ignoring the fact that <a href="http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/" rel="nofollow noreferrer">AddWithValue has some well-known shortcomings</a> (which we are perfectly aware of), are there any problems to be expected by using this approach? Did the designers of <code>SqlParameterCollection.AddWithValue</code> have a good reason not to do this "by default" which I am overlooking?</p>