0

I get the Error

Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and'System.DBNull'

with the Code (in the 3rd line)

DateTime? BirthDate = GetDate(PersonID);
System.Data.SqlClient.SqlCommand myCommand = new System.Data.SqlClient.SqlCommand(cStatement, myConnection);
myCommand.Parameters.AddWithValue("@BirthDate", BirthDate.HasValue ? BirthDate.Value : DBNull.Value);

How can i avoid this error?

c0rd
  • 1,329
  • 1
  • 13
  • 20
  • Also, this question answers this already: http://stackoverflow.com/questions/8669107/how-to-convert-a-nullable-datetime-variables-null-value-to-dbnull-value – Thorsten Dittmar Sep 07 '16 at 09:36

2 Answers2

3

You can cast it to object:

 myCommand.Parameters.AddWithValue("@BirthDate", BirthDate.HasValue ? (object) BirthDate.Value : (object) DBNull.Value);

The reason behind the error is that each result of your expression

condition ? result1 : result2;

Has a different type, so the compiler cannot work out the return type of it. By casting to object you are allowing the compiler to infer that the return type is object as both results of the expresion belongs to that type (every class inherits from object)

Juan
  • 3,675
  • 20
  • 34
1

Cast to an object.

DateTime? BirthDate = GetDate(PersonID);
System.Data.SqlClient.SqlCommand myCommand = new System.Data.SqlClient.SqlCommand(cStatement, myConnection);
myCommand.Parameters.AddWithValue("@BirthDate", BirthDate.HasValue ? (object)BirthDate.Value : DBNull.Value);
Maarten
  • 22,527
  • 3
  • 47
  • 68