Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Sized/Typed SqlParameters

Tags:

c#

.net

sqlclient

I'm trying to create an array of dbTyped and sized SqlParameters. This works fine but results in changing code both places if I need another column.

SqlParameter[] parameters = {
                                  new SqlParameter("@first_name", SqlDbType.VarChar, 50),
                                  new SqlParameter("@last_name", SqlDbType.VarChar, 50),
                                  new SqlParameter("@middle_name", SqlDbType.VarChar, 50),
                                  new SqlParameter("@empid", SqlDbType.Int)
                            };
parameters[0].Value = to.FirstName;
parameters[1].Value = to.LastName;
parameters[2].Value = to.MiddleName;
parameters[3].Value = to.EmpId;

What is a better way of doing this?

like image 550
Jason Eades Avatar asked Aug 02 '12 18:08

Jason Eades


1 Answers

You can use object initializer expressions:

SqlParameter[] parameters =
{    
  new SqlParameter("@first_name", SqlDbType.VarChar, 50) { Value = to.FirstName },
  new SqlParameter("@last_name", SqlDbType.VarChar, 50) { Value = to.LastName },
  new SqlParameter("@middle_name", SqlDbType.VarChar, 50) { Value = to.MiddleName },
  new SqlParameter("@empid", SqlDbType.Int) { Value = to.EmpId }
};

You could also create a list in the same way, which is often preferred:

List<SqlParameter> parameters = new List<SqlParameter>
{    
  new SqlParameter("@first_name", SqlDbType.VarChar, 50) { Value = to.FirstName },
  new SqlParameter("@last_name", SqlDbType.VarChar, 50) { Value = to.LastName },
  new SqlParameter("@middle_name", SqlDbType.VarChar, 50) { Value = to.MiddleName },
  new SqlParameter("@empid", SqlDbType.Int) { Value = to.EmpId }
};

Or you could even write an extension method on SqlParameter:

public static SqlParameter WithValue(this SqlParameter parameter, object value)
{
    parameter.Value = value;
    return parameter;
}

Then use it like this:

List<SqlParameter> parameters = new List<SqlParameter>
{    
  new SqlParameter("@first_name", SqlDbType.VarChar, 50).WithValue(to.FirstName),
  new SqlParameter("@last_name", SqlDbType.VarChar, 50).WithValue = to.LastName)
  new SqlParameter("@middle_name", SqlDbType.VarChar, 50).WithValue(to.MiddleName),
  new SqlParameter("@empid", SqlDbType.Int).WithValue(to.EmpId)
};
like image 58
Jon Skeet Avatar answered Oct 20 '22 12:10

Jon Skeet