3

In researching the cause of a bug, I came across this line of code:

Status |= (int)states.Reading;

What is the "|=" operator in C#?

"Status" is defined thusly:

public static int Status 

...with an accessor and mutator (or "getter" and "setter"), while "states" is defined this way:

[Flags]
public  enum states
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

2 Answers2

10

It's the "bitwise logical OR" operator, as defined here.

x |= y is equivalent to x = x | y

Also, if you want to learn more about the "|" operator itself, you can do so here.

Ricky Mutschlechner
  • 4,291
  • 2
  • 31
  • 36
2

While using the enumerators if you have specified [Flags] attribute on top of an "enum" member, this enables the user to select more than one enumerators in a single go. What I mean is this:-

if this is your enumerator:-

[Serializable, DataContract(Namespace = "Company.Domain.LOB.Handler")]
[Flags]
public enum BankItemStatus
{
    [EnumMember]
    UnBatched,
    [EnumMember]
    Batched,
    [EnumMember]
    Sent,
    [EnumMember]
    ReplyReceived,
    [EnumMember]
    Closed
}

Now if you use the Enum like this:-

BankItemStatus bankItemStatus = BankItemStatus.UnBatched;
BankItemStatus bankItemStatus = BankItemStatus.Sent;

The final value preserved by bankItemStatus would be BankItemStatus.Sent. You can check it like this:-

if(bankItemStatus.UnBatched==BankItemStatus.UnBatched) //FALSE
if(bankItemStatus.Sent==BankItemStatus.Sent) //TRUE

Now if you do it like this:-

BankItemStatus bankItemStatus = BankItemStatus.UnBatched;
bankItemStatus |= bankItemStatus.Sent

You will see that bankItemStatus now has both the enum members. You can check it like this:-

if(bankItemStatus.UnBatched==BankItemStatus.UnBatched) //TRUE
if(bankItemStatus.Sent==BankItemStatus.Sent) //TRUE

Hope that helps in understanding the use of |= operator in C# (in context of Enumerators).

ajaysinghdav10d
  • 1,771
  • 3
  • 23
  • 33
  • Great answer, thanks; I once changed an answer I had marked as correct to another cat who provided a more detailed answer, and the original awarded answerer wept inconsolably, so I will leave the accepted answer as-is, although this one is great. BTW, "BatchItemStatus" should be "BankItemStatus" in the enum definition. – B. Clay Shannon-B. Crow Raven Jun 28 '13 at 16:13