开发者

Why has the overloaded Add been replaced with AddWithValue?

The overloaded method SqlParameterCollection.Add(String, Object) has been marked as d开发者_如何学Ceprecated 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.


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.


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.


I know is an old post, but you should read:

https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

Is says basically that AddWithValue could sometimes incorrectly infer the correct type. Use Add instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜