0

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?

Alexander
  • 88
  • 6

1 Answers1

-1
   cmd.Parameters.Add(new SqlParameter("@start_date", t.StartDate.HasValue?t.StartDate:DBNull.Value));
Shannon Holsinger
  • 2,293
  • 1
  • 15
  • 21
  • 1
    That won't compile (as OP already stated in the question) as long as you don't cast at least one of the two results of the ternary operator to something like `object`. – René Vogt Sep 12 '16 at 08:30
  • 1
    Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". – abarisone Sep 12 '16 at 08:56