I read the MSDN documentation and examples here and I know that the correct syntax for a Paramters.Add call is :
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;
Where you have to specify the Parameter Name, the SqlDbType AND the Value with .Value.
Now the correct syntax for a Parameters.AddWithValue call is :
command.Parameters.AddWithValue("@demographics", demoXml);
Single line and skip the Type part.
My Question is : How is it that when I do it like this,
command.Parameters.Add("@demographics", demoXml);
// .Add method with .AddWithValue syntax
I don’t get any compiling error and even weirder, everything seems to work properly when the code is executed ?
There is no difference in terms of functionality. In fact, both do this:
The reason they deprecated the old one in favor of
AddWithValueis to add additional clarity, as well as because the second parameter isobject, which makes it not immediately obvious to some people which overload ofAddwas being called, and they resulted in wildly different behavior.Take a look at this example:
At first glance, it looks like it is calling the
Add(string name, object value)overload, but it isn’t. It’s calling theAdd(string name, SqlDbType type)overload! This is because 0 is implicitly convertible to enum types. So these two lines:and
Actually result in two different methods being called.
1is not convertible to an enum implicitly, so it chooses theobjectoverload. With0, it chooses the enum overload.