Name for method that takes a string value and returns DBNull.Value || string

Posted by David Murdoch on Stack Overflow See other posts from Stack Overflow or by David Murdoch
Published on 2010-04-08T19:49:30Z Indexed on 2010/04/08 19:53 UTC
Read the original article Hit count: 237

Filed under:
|
|
|

I got tired of writing the following 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.
}*/

So, I wrote this:

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));

If this is a good way to go about doing this then what would you suggest as the method name? DBNullValueorStringIfNotNull is a bit verbose and confusing.

I'm also open to ways to alleviate this problem entirely. I'd LOVE to do this:

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? DBNull.Value : MiddleName);

but that won't work.

I've got C# 3.5 and SQL Server 2005 at my disposal if it matters.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET