1

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?

arc54
  • 41
  • 5

1 Answers1

13

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))
Dave Clark
  • 2,243
  • 15
  • 32
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Everything is better with extension methods :-) `public static class NullableExtensions { public static bool NullOrEqual(this T? nullable, T compareTo) where T: struct { return nullable == null || nullable.Value.Equals(compareTo); } }` – Zohar Peled Nov 08 '17 at 18:14
  • 1
    @ZoharPeled: I'm not sure - maybe in a very limited scope, but I tend to reserve extension methods for generally-useful code. This is pretty specific. – Jon Skeet Nov 08 '17 at 18:16
  • 1
    I guess it's a matter of opinion. To me, it seems that this kind of method is almost begging to be an extension method. IMHO, `NullOrEqual` is much more readable as an extestion method then as a "regular method". Also, I tend to use extension methods even if they are specific to a single project or assembly. As soon as a method needs to be used for the same type in more than one class, I usually consider it as a good candidate to be an extension method. – Zohar Peled Nov 08 '17 at 20:34
  • As for better naming, I'd prefer the slight modification `nullableEnumOne.EqualsNullOr(regularEnumOne)` – JBSnorro Nov 15 '17 at 16:59