Typically, given an enum such as the following:
[Flags]
public enum MyFlagEnum
{
FirstFlag = 1,
SecondFlag = 2,
ThirdFlag = 4,
FourthFlag = 8,
}
You would check to see if a flag is set for a given value like this:
MyFlagEnum flagValue = DetermineFlagValue(); // returns some enumerate value you want to check
if((flagValue & MyFlagEnum.SecondFlag) == MyFlagEnum.SecondFlag)
{
// SecondFlag was set, so handle it
}
This
code gets very busy, especially if you have a particularly long name
for either the enumeration or its flags (or both!). Fortunately, there
is a very simple extension method you can build for your enumerations
that will make your code look a lot cleaner:
public static class MyFlagEnumHelper
{
public static bool HasFlag(this MyFlagEnum item, MyFlagEnum query)
{
return ((item & query) == query);
}
}
Then, when you want to check if a flag is set:
MyFlagEnum flagValue = DetermineFlagValue(); // returns some enumerate value you want to check
if(flagValue.HasFlag(MyFlagEnum.SecondFlag))
{
// SecondFlag was set, so handle it
}
Cleaner
and easier to understand. Unfortunately the compiler tricks used to
create enums mean there's no generic extension method that can be used
for all enumerations; you're going to have to include a separate
extension method for each flag enumeration you create. Still, that's
what snippets are for, right? :)