I have defined Class Person property Birthday as nullable DateTime? , so why shouldn’t the null coalescing operator work in the following example?
cmd.Parameters.Add(new SqlParameter("@Birthday",
SqlDbType.SmallDateTime)).Value =
person.Birthday ?? DBNull.Value;
The compiler err I got was "Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'"
The following also got a compile error :
cmd.Parameters.Add(new SqlParameter("@Birthday",
SqlDbType.SmallDateTime)).Value =
(person.Birthday == null) ? person.Birthday:DBNull.Value;
I added a cast to (object) as recommended by Refactor, and it compiled, but didn’t work properly and the value was stored in the sqlserver db as null in both cases.
SqlDbType.SmallDateTime)).Value =
person.Birthday ?? (object)DBNull.Value;
Can someone explain what is going on here?
I needed to use the following clumsy code:
if (person.Birthday == null)
cmd.Parameters.Add("@Birthday", SqlDbType.SmallDateTime).Value
= DBNull.Value;
else cmd.Parameters.Add("@Birthday", SqlDbType.SmallDateTime).Value =
person.Birthday;