Search code examples
c#sqlparameter

Efficient way of providing SqlDbType?


I have this working code below. However, I there is no SqlParameter constructor that takes name, value, and SqlDbType and I want to just provide the type for the date parameters. Is there a way to do that which does not require adding a lot of code?

SqlParameter[] parameters =  
{
    new SqlParameter("@START_ORDER", startOrder),
    new SqlParameter("@END_ORDER", endOrder), 
    new SqlParameter("@START_ITEM", startItem), 
    new SqlParameter("@END_ITEM", endItem), 
    new SqlParameter("@START_DUEDATE", dateFrom), 
    new SqlParameter("@END_DUEDATE", dateTo)
};

Solution

  • new SqlParameter("@name", SqlDbType.Whatever) { Value = value }
    

    There are constructor overloads that take all kinds of parameters, but they are perhaps not worth the hassle of specifying each and every argument. The above is probably as simple as it gets.

    (Note that in some cases you might want to set SqlValue instead of Value.)