KA N
KA N

Reputation: 71

c# set two flags with one flag together

At the time I have 2 buttons for two flags. I want 1 button that set two flags

These are the flags:

if (InteractiveInput.Checked) flags |= CONNECT_INTERACTIVE;
if (PromptInput.Checked) flags |= CONNECT_PROMPT;

I want:

if (InteractiveInput.Checked) flags |= CONNECT_INTERACTIVE & CONNECT_PROMPT;'''

Upvotes: 0

Views: 870

Answers (1)

Ross Gurbutt
Ross Gurbutt

Reputation: 1029

Bitwise AND (&) means the combination for each bit where both are 1.
For enum flag values this usually gives 0/None because except for special cases, enum flag values are deliberately unique (bitwise) and as such have no bits matching with other enum values.

You want Bitwise OR:

if (InteractiveInput.Checked)
    flags |= CONNECT_INTERACTIVE | CONNECT_PROMPT;

Imagine the following example:

[Flags]
public enum AdditionalCarParts
{
    None,
    AirConditioning,
    Sunroof,
    RearDoors
}

This is implicity defined as:

[Flags]
public enum AdditionalCarParts
{
    None = 0,
    AirConditioning = 1,
    Sunroof = 2,
    RearDoors = 4
}

Or in binary:

  0
  1
 10
100

As you can see, none of these have a bit that match, and therefore AND will never return anything other than None(0).

Two examples of combining them bitwise using the different operators:

AirConditioning (decimal: 1, binary: 001) & Sunroof (decimal: 2, binary: 010) = None (decimal: 0, binary: 000)  

AirConditioning (decimal: 1, binary: 001) | Sunroof (decimal: 2, binary: 010) = AirConditioning | Sunroof (decimal: 3, binary: 011)

Upvotes: 6

Related Questions