2

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.

Community
  • 1
  • 1
cdub
  • 24,555
  • 57
  • 174
  • 303
  • 2
    http://stackoverflow.com/questions/9999751/difference-between-parameters-add-and-parameters-addwithvalue looks like the best answer i could find – mmeasor Dec 05 '12 at 21:44

2 Answers2

4

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.

MatthewT
  • 638
  • 6
  • 17
Tigran
  • 61,654
  • 8
  • 86
  • 123
  • so how does it handle the type now? – cdub Dec 05 '12 at 21:45
  • so don't use the first, only the second and ignore the type now is what microsoft is saying? – cdub Dec 05 '12 at 21:46
  • @chris: well, specifying a real type is always better, imo. What about this functions, it's just a simple substitude to the overload of the `Add`. In other words, it's kind of *refactoring* was done in framework to make API clear. – Tigran Dec 05 '12 at 21:50
2

Perhaps this rticle will help http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx

ajp
  • 1,440
  • 2
  • 13
  • 25