I have a if condition for a Enum. My enum is :
public enum EmploymentType
{
Type1 = 1,
Type2 = 2,
Type3 = 3
}
and this condition
EmploymentType type = EmploymentType.Type1 ;
if (type.HasFlag(EmploymentType.Type1 | EmploymentType.Type2 )) //if (type == (EmploymentType.Type1 | EmploymentType.Type2 ))
{
return true;
}
else
{
return false;
}
Expected true result for this condition, but result is false. Why?
There’s a few things you are doing wrong here:
Your enumeration does not have the
[Flags]attribute. HasFlags is designed to work only with enumerations with this attribute set.You don’t follow the flag conventions. Unless
Type3is a combination ofType1andType2, it should have value4instead of3. Read up on the documentation in the FlagsAttribute MSDN page.Your expectations are wrong:
HasFlag(Flag1 | Flag2)returns only true of both Flag1 and Flag2 are set, since you are bitwise OR-ing Flag1 and Flag2 and checking if these bits are set. Please have a look at the HasFlag documentation for details.I suspect that your enum is meant to be just an enum and not a container for flags. Flags are supposed to be combinable, i.e., type could be “Type1 and Type2” or “no type” or “all types” (like font formatting, which can be “none”, “bold”, “italic” as well as “bold and italic”, “bold and underlined”, etc.). I don’t think that applies to your case.
So, forget about the flags thing and just use regular enum matching (such as
type == EmploymentType.Type1 || type == EmploymentType.Type2or aswitchstatement) instead of theHasFlagsmethod.