I'm encountering an interesting scenario with the CA1508 warning in C# when using a switch expression with a nullable DateTime property. Specifically, I have a property that determines if there are pending updates based on the comparison of two DateTime values. However, the way I handle the null check in the switch expression seems to affect whether I receive a CA1508 warning or not.
Here's a simplified version of my class:
public class Record
{
public DateTime? OurLastUpdateDate { get; set; }
public DateOnly? TheirLastUpdateDate { get; set; }
public bool HasPendingUpdates => OurLastUpdateDate switch
{
not null => DateOnly.FromDateTime(OurLastUpdateDate.Value) < TheirLastUpdateDate,
null => true,
};
}
With this implementation, I do not receive a warning:
public bool HasPendingUpdates => OurLastUpdateDate switch
{
not null => DateOnly.FromDateTime(OurLastUpdateDate.Value) < TheirLastUpdateDate,
_ => true,
};
However, changing the null check to explicitly check for null like this triggers a CA1508 warning:
public bool HasPendingUpdates => OurLastUpdateDate switch
{
not null => DateOnly.FromDateTime(OurLastUpdateDate.Value) < TheirLastUpdateDate,
null => true,
};
I'm curious as to why the explicit null check results in a warning, while the wildcard _ does not, even though they seem equivalent. I suspect it might be related to DateTime being a value type, but it feels like a compiler issue. Any insights or explanations would be greatly appreciated!
It's nothing to do with value types, you can produce exactly the same situation with e.g.
string(orstring?if using nullable reference types).It's simply that we already know before the second branch is evaluated that the value must be null - any non-null value has been consumed by the first branch. As such, as the warning says, this is dead conditional code, and it's clearer to express "in all other situations" as the discard pattern
_- rather than for you to manually cover those other situations by expressing some logic.Now, you may feel that your
nullcondition is more expressive, and if so you can feel free to suppress the warning there.