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

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

Upvotes: 3

Views: 202

Answers (2)

ajaysinghdav10d
ajaysinghdav10d

Reputation: 1957

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).

Upvotes: 2

Ricky Mutschlechner
Ricky Mutschlechner

Reputation: 4409

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.

Upvotes: 10

Related Questions