I defined the Person property of the Person class as a null DateTime? , so why does the null coalescence operator not work in the following example?
cmd.Parameters.Add(new SqlParameter("@Birthday", SqlDbType.SmallDateTime)).Value = person.Birthday ?? DBNull.Value;
The compiler error I received was "Operator" ?? can't apply to operands like "System.DateTime"? and 'System.DBNull' "
The following also received a compilation error:
cmd.Parameters.Add(new SqlParameter("@Birthday", SqlDbType.SmallDateTime)).Value = (person.Birthday == null) ? person.Birthday:DBNull.Value;
I added the actuation (object), as recommended by Refactor, and it compiled but did not work properly, and the value was stored in 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;
c # dbnull null-coalescing-operator
Lill lansey
source share