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);
        parameterCollection.AddWithValue(parameterName, value);

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

About battenworks
I'm a software developer and craftsman living in Salt Lake City, UT. When I'm not working with computers, I enjoy billiards and motocross/supercross racing. I am a regular attendee at local geek events, where I occassionally give presentations.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: