Sometimes I find myself wanting a quick way to compare an enum with a list of other enums… Basically, if the enum is one of these, then do this. It’s pretty easy to do with Linq, but if you want to do it a few times in a few other places, it pays to be DRY and make an extension method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class EnumExtensions | |
{ | |
public static bool IsOneOf(this Enum theEnum, params Enum[] enums) | |
{ | |
return enums.Any(e => e.Equals(theEnum)); | |
} | |
} |
Note that you want to use .Equals and not ==. You can use == when you know the enum type, but if you’re creating a generic extension method to use with all enums, it won’t work.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum MyEnum | |
{ | |
First = 1, | |
Second = 2 | |
} | |
public bool AreEqual(Enum first, Enum second) | |
{ | |
return first == second; | |
} | |
public bool Equals(Enum first, Eunm second) | |
{ | |
return first.Equals(second); | |
} | |
// ... | |
MyEnum myEnum1 = MyEnum.First; | |
myEnum1 == MyEnum.First; // True | |
AreEqual(myEnum1, MyEnum.First); // False | |
Equals(myEnum1, MyEnum.First); // True |
I don’t unremarkably comment but I gotta say regards for the post on this one :
D.