FROM#?? zero coalescing operator question

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; 
+7
c # dbnull null-coalescing-operator
source share
3 answers

The problem is what is a DateTime? and DBNull.Value are not the same type, so you cannot use the null coalescing operator on them.

In your case, can you do person.Birthday ?? (object)DBNull.Value person.Birthday ?? (object)DBNull.Value to pass a value of type object via Add()

+20
source share

Your first problem is that for the operator ?? or ?: objects for any choice must be of the same type. Here they are different.

+3
source share

I prefer to iterate over my parameters immediately before executing the query, changing, if necessary, all null instances to DBNull, for example:

 foreach (IDataParameter param in cmd.Parameters) if (param.Value == null) param.Value = DBNull.Value; 

This allows me to leave the as-is values ​​zero and just change them later.

+3
source share

All Articles