Array of Sized/Typed SqlParameters

Jason Eades picture Jason Eades · Aug 2, 2012 · Viewed 25.6k times · Source

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?

Answer

Jon Skeet picture Jon Skeet · Aug 2, 2012

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)
};