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

7

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

public enum Status
{
    Running = 1,
    Inactive = 2,
    Error = Inactive | Running
}
    
asked by anonymous 10.07.2014 / 21:19

1 answer

17

This is not the logical operator "or" (which is represented by || ). This is the bitwise or (or all bits) operator, 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 Error field with a value of 3 .

This is mostly used in enums declared with the [Flags] attribute, and in that case it does not seem very indicated (since if the status is a Error this probably means that the status will not be Running ). Using flags enum is recommended when you have non-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
}
    
10.07.2014 / 21:30