0

When adding a parameter to an OLEDB command, is there a need to use 'new'. Both of the following work. Is one preferable or are they doing the same thing?

command.Parameters.Add(new OleDbParameter("name", OleDbType.VarChar)); 
command.Parameters.Add("name", OleDbType.VarChar);
3
  • There is no difference in how both the approach works. It for your convenience of what you want to use. If you have a separate method of creating parameters then you use the first approach else use the second approach Commented May 15, 2019 at 10:09
  • 1
    You can look at the source code: referencesource.microsoft.com/#System.Data/fx/src/data/System/… Notice how the method returns the parameter just created. This allows this syntax command.Parameters.Add("name", OleDbType.VarChar).Value = "YourValue"; Commented May 15, 2019 at 10:10
  • @Steve Im bookmarking that website, nice comment Commented May 15, 2019 at 10:32

1 Answer 1

1

Yes, Add(string, OleDbType) overload calls the Add(OleDbParameter) overload. That means they do the same thing under the hood.

public OleDbParameter Add(string parameterName, OleDbType oleDbType)
{
     return Add(new OleDbParameter(parameterName, oleDbType));
}

https://referencesource.microsoft.com/#System.Data/fx/src/data/System/Data/OleDb/OleDbParameterCollection.cs,78

As Steve commented, most common way to use it (as far as I see) like;

command.Parameters.Add("name", OleDbType.VarChar).Value = "YourValue";

or if you know (of specify) your db column size (let's assume it is varchar(10)), you can add an integer as a third parameter like calling the Add(parameterName, oleDbType, size) overload;

command.Parameters.Add("name", OleDbType.VarChar, 10).Value = "YourValue";
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, I have multiple rows to add, so my intention is to declare the parameter then add the value in a subsequent loop with command.Parameters["name"].Value = "value" . I'm still unsure which is preferable in this instance.
@Bobney You can use Parameters.AddRange approach for this since this method takes new OleDbParameter[] as a parameter.
@SonerGönül Your last comment did misunderstand the OP intention. To reuse the parameter he/she should var parameter = command.Parameters.Add("name", OleDbType.VarChar); and inside the loop parameter.Value = "whatever";
@bradbury9 Oh, okay then. But in such a case, the parameter name, parameter value and OleDbType should exist in the structure of the object that you want to iterate.
Thanks, but all 3 methods (now including var parameter = command.Parameters.Add("name", OleDbType.VarChar);) seem to work. Is it just a case of convenience?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.