I have two nullable enums which I would like to compare the value of to two regular enums. If the nullable enums do not have a value, I want the comparison to evaluate to true. This is what my logic looks like so far:
if (!nullableEnumOne.HasValue || nullableEnumOne.Value == regularEnumOne)
&& (!nullableEnumTwo.HasValue || nullableEnumTwo.Value == regularEnumTwo)
{
//do something
}
Is there a way to simplify this logic which I am missing?
It's probably simplest to use the null-coalescing operator to "default" to the value that you're comparing against:
if ((nullableEnumOne ?? regularEnumOne) == regularEnumOne &&
(nullableEnumTwo ?? regularEnumTwo) == regularEnumTwo)
Or stick with your current code... or compare against null
instead of using a negative condition:
if ((nullableEnumOne == null || nullableEnumOne.Value == regularEnumOne)
&& ((nullableEnumTwo == null || nullableEnumTwo.Value == regularEnumTwo))
Or slightly weirdly, you could call Equals
with the null conditional operator, using the null coalescing operator to make the null case true:
if ((nullableEnumOne?.Equals(regularEnumOne) ?? true)
&& (nullableEnumTwo?.Equals(regularEnumTwo) ?? true))
None of these are massively readable, admittedly. I'd be tempted to write a helper method, so you can write:
if (NullOrEqual(nullableEnumOne, regularEnumOne) &&
NullOrEqual(nullableEnumTwo, regularEnumTwo))
See more on this question at Stackoverflow