title: How do I Parameterize a null string with DBNull.Value clearly and quickly
body: <p>I got tired of writing the following code:</p>
  
  <pre><code>/* Commenting out irrelevant parts
  public string MiddleName;
  public void Save(){
      SqlCommand = new SqlCommand();
      // blah blah...boring INSERT statement with params etc go here. */
      if(MiddleName==null){
          myCmd.Parameters.Add("@MiddleName", DBNull.Value);
      }
      else{
          myCmd.Parameters.Add("@MiddleName", MiddleName);
      }
      /*
      // more boring code to save to DB.
  }*/
  </code></pre>
  
  <p>So, I wrote this:</p>
  
  <pre><code>public static object DBNullValueorStringIfNotNull(string value)
  {
      object o;
      if (value == null)
      {
          o = DBNull.Value;
      }
      else
      {
          o = value;
      }
      return o;
  }
  
  // which would be called like:
  myCmd.Parameters.Add("@MiddleName", DBNullValueorStringIfNotNull(MiddleName));
  </code></pre>
  
  <p><strong>If this is a good way to go about doing this then what would you suggest as the method name? <em>DBNullValueorStringIfNotNull</em> is a bit verbose and confusing.</strong></p>
  
  <p>I'm also open to ways to alleviate this problem entirely. I'd LOVE to do this:</p>
  
  <pre><code>myCmd.Parameters.Add("@MiddleName", MiddleName==null ? DBNull.Value : MiddleName);
  </code></pre>
  
  <p>but that won't work because the "Operator '??' cannot be applied to operands of type 'string and 'System.DBNull'".</p>
  
  <p>I've got C# 3.5 and SQL Server 2005 at my disposal if it matters.</p>