views:

263

answers:

2

Which approach is recommended:

void Add(int? value)
{
   command.Parameters.Add("@foo").Value = value;
}

or

void Add(int? value)
{
   command.Parameters.Add("@foo").Value = (object)value ?? DBNull.Value;
}
+2  A: 

If you want to pass a null value in a parameter, you need to pass DBNull.Value as in your second example.

If you assign null as the parameter value, the parameter will not be sent to the procedure, which will make the procedure call to either fail (if the parameter is required) or use the default value for the parameter, which may or may not be null.

Fredrik Mörk
+1  A: 

It depends on the functionality you want.

If you pass null as the value then the SqlCommand will treat that the same as if the parameter hadn't been passed at all. If it's a required parameter in, for example, a stored procedure then that will cause your query to fail.

If you pass DBNull.Value then the SqlCommand will treat that as SQL null being passed.

Dave