Ehsan
Ehsan

Reputation: 3491

How use flag in if condition

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?

Upvotes: 1

Views: 4246

Answers (4)

JnManso
JnManso

Reputation: 23

When you use [Flags] the enum value must be in Base 2 (Binary)


    [Flags]
    enum Days2
    {
        None = 0x0,
        Sunday = 0x1,
        Monday = 0x2,
        Tuesday = 0x4,
        Wednesday = 0x8,
        Thursday = 0x10,
        Friday = 0x20,
        Saturday = 0x40
    }

    [Flags]
    public enum Pet {
       None = 0,
       Dog = 1,
       Cat = 2,
       Bird = 4,
       Rabbit = 8,
       Other = 16
    }

Upvotes: 1

Heinzi
Heinzi

Reputation: 172280

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 Type3 is a combination of Type1 and Type2, it should have value 4 instead of 3. 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.Type2 or a switch statement) instead of the HasFlags method.

Upvotes: 3

user743382
user743382

Reputation:

| does not mean what you think it does, and is probably best left unexplained right now. What matters is that to test "if a or b", you can use if (a || b):

if (type == EmploymentType.Type1 || type == EmploymentType.Type2)
{
    ...
}

Upvotes: 0

Your enumeration does not have the [Flags] attribute.

Also change your if statement to

if (type.HasFlag(EmploymentType.Type1) || type.HasFlag(EmploymentType.Type2))

Upvotes: 1

Related Questions