Search code examples
c#nullablec#-6.0c#-7.0null-coalescing-operator

Null coalescing Operator on DateTime c#


I personally like the null coalescing Operator and I try to use it in my getters. But it seems to be restricted to certain Datatypes. For Instance following isn't building:

public DateTime From => Settings.Default.StartDate ?? DateTime.Today;

Error CS0019 Operator '??' cannot be applied to operands of type 'DateTime' and 'DateTime'

and following is:

public DateTime From => Settings.Default.StartDate == null ? DateTime.Today : Settings.Default.StartDate;

Anybody has a clue why? Is it just not yet implemented or am I missing the logic here?


Solution

  • The null coalescing operator (??) only works if the expression to the left of the operator is nullable.

    The error message:

    Error CS0019 Operator '??' cannot be applied to operands of type 'DateTime' and 'DateTime'

    shows that Settings.Default.StartDate is not nullable - it is a DateTime.

    As such, you need to change StartDate to be a nullable DateTime instead (i.e. DateTime?).

    OK, but why then does:

    public DateTime From => Settings.Default.StartDate == null ? DateTime.Today : Settings.Default.StartDate;
    

    compile?

    The short answer is that it is nonsensical but technically valid. The comparison to null will always be false (since a DateTime will never be null) and thus Settings.Default.StartDate will always be returned. It is just a convoluted way of writing:

    public DateTime From => Settings.Default.StartDate;
    

    So why doesn't ?? do the same thing? (i.e. let you use ?? when it doesn't really make sense to use it) Basically because it isn't defined that way - it doesn't want to allow you to do a nonsensical thing, so the compiler detects and blocks it.