C# SqlParameters Short Hand

You have a bigger constructor:

 command.Parameters.Add(
    "@CategoryName", SqlDbType.VarChar, 80).Value = "toasters";

Using the method AddWithValue will make the code a little bit shorter:

command.Parameters.AddWithValue("@CURSTAT", record.curstat);
//...

I do it a bit differntly.

I have both a extension method and a static method to create SqlParameters.

public static SqlParameter ToParam(this object v,string name){
return new SqlParameter(name,v);
}

Then I do something like this:

var p = new List<SqlParameter>();
p.Add(record.curstat.ToParam("@curstat"));
p.Add(record.itemdesc.ToParam("@itemdesc"));
//etc...

command.Parameters.AddRange(p.ToList());

Tags:

C#

Sql

Parameters