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?
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)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With