7
What the logical operator |
(or) does so in that Enum?
public enum Status
{
Running = 1,
Inactive = 2,
Error = Inactive | Running
}
7
What the logical operator |
(or) does so in that Enum?
public enum Status
{
Running = 1,
Inactive = 2,
Error = Inactive | Running
}
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
}
Browser other questions tagged c# enums
You are not signed in. Login or sign up in order to post.
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 methodHasFlag
(if(textAttribute.HasFlag(TextAttributes.Bold))
).– dcastro