Writing data layer code against T-SQL, I often have to add a SqlParameter
to a SqlCommand
. In the case of a nullable type (for example a DateTime?
), I write it like this:
if (t.StartDate.HasValue)
cmd.Parameters.Add(new SqlParameter("@start_date", t.StartDate));
else
cmd.Parameters.Add(new SqlParameter("@start_date", DBNull.Value));
I can't use the ternary operator ?:
, as the IntelliSense/compiler will complain that "there is no implicit conversion between type 'System.DateTime?' and 'System.DBNull'.
Is there a shorter/neater way of writing my 4 lines of code?