What does |= (single pipe equal) and &=(single ampersand equal) mean

C#OperatorsBitwise Operators

C# Problem Overview


In below lines:

//Folder.Attributes = FileAttributes.Directory | FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReadOnly;
Folder.Attributes |= FileAttributes.Directory | FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReadOnly;


Folder.Attributes |= ~FileAttributes.System;
Folder.Attributes &= ~FileAttributes.System;

What does |= (single pipe equal) and &= (single ampersand equal) mean in C#?

I want to remove system attribute with keeping the others...

C# Solutions


Solution 1 - C#

They're compound assignment operators, translating (very loosely)

x |= y;

into

x = x | y;

and the same for &. There's a bit more detail in a few cases regarding an implicit cast, and the target variable is only evaluated once, but that's basically the gist of it.

In terms of the non-compound operators, & is a bitwise "AND" and | is a bitwise "OR".

EDIT: In this case you want Folder.Attributes &= ~FileAttributes.System. To understand why:

  • ~FileAttributes.System means "all attributes except System" (~ is a bitwise-NOT)
  • & means "the result is all the attributes which occur on both sides of the operand"

So it's basically acting as a mask - only retain those attributes which appear in ("everything except System"). In general:

  • |= will only ever add bits to the target

  • &= will only ever remove bits from the target

Solution 2 - C#

a |= b is equivalent to a = a | b except that a is evaluated only once
a &= b is equivalent to a = a & b except that a is evaluated only once

In order to remove the System bit without changing other bits, use

Folder.Attributes &= ~FileAttributes.System;

~ is bitwise negation. You will thus set all bits to 1 except the System bit. and-ing it with the mask will set System to 0 and leave all other bits intact because 0 & x = 0 and 1 & x = x for any x

Solution 3 - C#

> I want to remove system attribute with keeping the others..

You can do this like so:

Folder.Attributes ^= FileAttributes.System;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSilverLightView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Armen TsirunyanView Answer on Stackoverflow
Solution 3 - C#Chris SView Answer on Stackoverflow