The operator '??' cannot be applied to operands of type "System.DateTime"

I get the following error:

Operator '??' cannot be applied to operands of type 'System.DateTime' 

  foreach (EndServReward r in reward) { if (con.State == ConnectionState.Closed) { con.Open(); } myIfxCmd.Parameters[0].Value = r.EmpNum ; myIfxCmd.Parameters[1].Value = (r.ServDate) ?? DBNull.Value; } 

where reward is List<EndServReward> reward , why is this happening and how to fix it?

+6
source share
6 answers

?? - operator of zero coalescence.
It makes no sense to apply it to a value that cannot be null .

+11
source

The nullcoalescing operator cannot be applied by default to a type that is not inherently null, such as DateTime . If you still want to use it, you will need to consider using DateTime as a type with a null value, using, for example, DateTime? dt; DateTime? dt;

+6
source

The r.ServDate property must be NULL:

 public DateTime? ServDate { get; set; } 

The default DateTime is not Nable.

+3
source

You can either change the type to nullable, as suggested in other answers, or add a helper method to your code:

 private bool IsDefault<T>(T value) { if (value == null) return false; return value.Equals(default(T)); } 

Then change the code to this:

 myIfxCmd.Parameters[1].Value = IsDefault<DateTime>(r.ServDate) ? (object)DBNull.Value : (object)r.ServDate; 
+3
source

DateTime is a ValueType value. The type of the value is not NULL - they always have some value.

This is the same for integers, doubles, etc.

The statement you are using checks to see if it is null, so this is optional.

However, you might consider checking the value against a base value, such as Min. You really should consider what the default value of this variable is, if appropriate, and then check for it.

Consider int again. You do not check it against null, but you can check it for zero or negatives.

+2
source

As the other answers correctly say, you cannot use the Null-Coalescing operator for the value type -DateTime.

Before trying to assign myIfxCmd.Parameters[1].Value using Null . The first question is that you set the default value for the ServDate property in the EndServReward Class? Rather, converting to Null or DateTime.Min best to set the default value for ServData when creating the object itself. This will help determine functionality in one place and provide a consistent solution.

You can select it as DateTime.Min or Null when it is created, and not when it is updated in the database.

+1
source

Source: https://habr.com/ru/post/956821/


All Articles