Place a Null Value in a SqlParameter with an Extension Method

I had to write some straight-up ADO-type code today to talk to SQL Server. Some of the values I’m passing into a stored procedure can be null, and as we’ve all experienced, the .AddWithValue() method doesn’t coerce null to DBNull.Value on its own. And by “we’ve”, I mean all of us who program in .NET, of course.

So, I wrote a simple extension method that uses DBNull.Value in the case where the value passed to the method is null:

publicstaticvoid AddWithNullableValue(this SqlParameterCollection parameterCollection, string parameterName, object value)
{
    if (null == value)
        parameterCollection.AddWithValue(parameterName, DBNull.Value);
    else
        parameterCollection.AddWithValue(parameterName, value);
}

Nothing ground-breaking, by any means. But, it sure does clean up my code. Hope it helps someone else.