3

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
  • 1
    The code in your second example doesn't compile -- instead you get "Operator '??' cannot be applied to operands of type 'int?' and 'System.DBNull'." To make it work, you need to cast value as object, e.g. (object)value ?? DBNull.Value;. Commented Mar 3, 2010 at 16:33
  • @Mike Powell: Hi. Indeed you're right. My existing code is exactly as you mentioned. I just forgot to write it correctly. Commented Mar 3, 2010 at 16:42

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.