1

I have SQL parameter array as...

SqlParameter[] sqlParams = new SqlParameter[2];

If I want to add more parameters, Can I add to the current array ?

3 Answers 3

12

No you cannot append elements. In .NET arrays are static. If you want dynamic collections you could use a generic List<T> to which you could add elements dynamically.

var sqlParams = new List<SqlParameter>();
sqlParams.Add(param1);
sqlParams.Add(param2);
...

// convert to a static array if needed
SqlParameter[] result = sqlParams.ToArray();
Sign up to request clarification or add additional context in comments.

3 Comments

& you can Use .ToArray() if you need to
But, How do I pass it to "Parameters" property of sqlCommand ?
@Anish, he showed you how to convert to an array afterwards. sqlCommand.Parameters.AddRange(sqlParams.ToArray());
3

Probably better to use a System.Collections.Generic.List<>

List<SqlParameter> sqlParams = new List<SqlParameter>();
sqlParams.Add(x);
sqlParams.Add(y);
sqlParams.Add(z);

If you need an array, you can always go:

sqlParams.ToArray();

Comments

1

Actually, I would just use the built in Parameters property of SqlCommand.

    System.Data.SqlClient.SqlConnection connection 
        = new System.Data.SqlClient.SqlConnection("connection string goes here");
    System.Data.SqlClient.SqlCommand command = connection.CreateCommand();

    System.Data.SqlClient.SqlParameter parameter = command.CreateParameter();
    parameter.ParameterName = "@ParameterName";
    parameter.DbType = DbType.String;
    parameter.Value = "Some String Value";

    command.Parameters.Add(parameter);

Then later, if you need to access them, you can do so by:

SqlParameter param = command.Parameters[0];

That way you don't have to mess with adding a range and keeping track of a separate array or List<>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.