views:

22

answers:

2

The overloaded method SqlParameterCollection.Add(String, Object) has been marked as deprecated since version 3.5 SP1 of the .NET Framework. You should use the AddWithValue() method that was introduced with version 2.0.

Is there a good reason why the Add(String, Object) has been replaced with a AddWithValue()? I'm fine with the change, but I am curious about why the change was made.

+3  A: 

I would think that it's because of the possibility for misuse described in the MSDN docs you referenced:

Use caution when you are using this overload of the SqlParameterCollection.Add method to specify integer parameter values. Because this overload takes a value of type Object, you must convert the integral value to an Object type when the value is zero, as the following C# example demonstrates.

parameters.Add("@pname", Convert.ToInt32(0));

If you do not perform this conversion, the compiler assumes that you are trying to call the SqlParameterCollection.Add (string, SqlDbType) overload.

In fact the docs you referenced for the new API say as much:

The overload of Add that takes a string and an object was deprecated because of possible ambiguity with the SqlParameterCollection.Add overload that takes a String and a SqlDbType enumeration value where passing an integer with the string could be interpreted as being either the parameter value or the corresponding SqlDbType value.

Steve Townsend
A: 

I believe it was due to ambiguity due to the value being passed via Object, and other overloads of Add(). I can recall having situations where I was unintentionally calling a different version of Add() because the value I was passing happened to be of a different, more specific data type.

Andrew Barber