What does the "OR" operator do in an Enum?

Asked

Viewed 204 times

7

What the logical operator | (or) does so in that Enum?

public enum Status
{
    Running = 1,
    Inactive = 2,
    Error = Inactive | Running
}

1 answer

17


This is not the logical operator "or" (which is represented by ||). This is the operator of "bitwise or" ("or all bits"), and it performs this operation on the numbers.

1 = 0000 0001 (binário)
2 = 0000 0010 (binário)
1 | 2 = 0000 0011 (binário) = 3

Then the above statement defines the field Error with a value 3.

This is mostly used in enums declared with the attribute [Flags], and in this case it does not seem very indicated (since if the status is a Error this probably means that the status will not be Running). The use of Enum flags is recommended when you have not mutually exclusive options. For example, see the statement below:

[Flags]
public enum TextAttributes
{
    None = 0,
    Bold = 1,
    Italic = 2,
    Underline = 4,
    BoldAndItalic = Bold | Italic,
    BoldAndUnderline = Bold | Underline,
    ItalicAndUnderline = Italic | Underline,
    All = Bold | Italic | Underline
}
  • 2

    I would like to add: to check whether a enum contains a particular flag, the bitwise and (if((textAttribute & TextAttributes.Bold) == TextAttributes.Bold)) or the method HasFlag (if(textAttribute.HasFlag(TextAttributes.Bold))).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.