Difference between SqlParameter.Add and AddWithValue

cdub picture cdub · Dec 5, 2012 · Viewed 9.6k times · Source

Possible Duplicate:
Difference between Parameters.Add and Parameters.AddWithValue

From MSDN code, what is the difference between these two:

    SqlCommand command = new SqlCommand(commandText, connection);

    //#1        
    command.Parameters.Add("@ID", SqlDbType.Int);
    command.Parameters["@ID"].Value = customerID;

    //#2
    command.Parameters.AddWithValue("@demographics", demoXml);

Is it better to do the first one to make sure I am casting the parameter corrctly? I'm trying to make my code more secure.

Answer

Tigran picture Tigran · Dec 5, 2012

According to the MSDN:

AddWithValue replaces the SqlParameterCollection.Add method that takes a String and an Object. 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. Use AddWithValue whenever you want to add a parameter by specifying its name and value.

So the AddWithValue replaces deprecated overload that create ambiguity.