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? :)
------
Not sure what the protocol is on MSDN for responding to a post, so I'm just editing in my response. You don't need the "== value" portion, the "a & b" will return 0 or non-zero, meaning you can use it as a simple conditional. Or if you're really picky, you can use "!= 0" or "> 0" to indicate a "true" result. This way you can also check for multiple settings in the same conditional test. All of this is pretty standard bitmask interaction going back decades. For example:
MyFlagEnum flagValue = DetermineFlagValue();
if((flagValue & MyFlagEnum.SecondFlag) > 0)
{
// SecondFlag was set, so handle it
}