Exitos
Exitos

Reputation: 29750

What does | (pipe) mean in c#?

Just wondering what the pipe means in this? ive never seen it before:

FileSystemAccessRule fullPermissions = new FileSystemAccessRule(
             "Network Service",
             FileSystemRights.FullControl | FileSystemRights.Modify,
             AccessControlType.Allow);

Cheers

Upvotes: 18

Views: 16372

Answers (6)

Jackson Pope
Jackson Pope

Reputation: 14660

For an enum marked with the [Flags] attribute the vertical bar means 'and', i.e. add the given values together.

Edit: This is a bitwise 'or' (though semantically 'and'), e.g.:

[Flags]
public enum Days
{
     Sunday    = 0x01,
     Monday    = 0x02,
     Tuesday   = 0x04,
     Wednesday = 0x08,
     Thursday  = 0x10,
     Friday    = 0x20,
     Saturday  =  0x40,
}

// equals = 2 + 4 + 8 + 16 + 32 = 62
Days weekdays = Days.Monday | Days.Tuesday | Days.Wednesday | Days.Thursday | Days.Friday;

It's a bitwise-OR but semantically you think of it as an AND!

Upvotes: 18

kemiller2002
kemiller2002

Reputation: 115538

I'm assuming you mean this: FileSystemRights.FullControl | FileSystemRights.Modify

This FileSystemRights, is an enum with FullControl and Modify having their own numeric values.

So if FullControl = 1 and Modify = 2,

FileSystemRights.FullControl | FileSystemRights.Modify = 3.  
00000001 | 00000010 = 00000011.  

Each bit is a "flag" for the method. The input checks to see which "flag" is set and what to do.

So in this example, position 1 (the digit all the way on the right in this case) is FullControl, and position 2 is Modify. The method looks at each of the positions, and changes it behavior. Using flags is a way of passing in multiple parameters of behaviors without having to create a parameter for each possiblity (e.g. bool allowFullControl, bool allowModify) etc.

Bitwise Operator

Upvotes: 3

Achim
Achim

Reputation: 15722

It's a boolean or. FullControl and Modify represent bits in a mask. For example 0001 and 0101. If you would combine those via pipe, you would get 0101.

Upvotes: 1

Rhapsody
Rhapsody

Reputation: 6077

It's a binary operator:

Binary | operators are predefined for the integral types and bool. For integral types, | computes the bitwise OR of its operands. For bool operands, | computes the logical OR of its operands; that is, the result is false if and only if both its operands are false.

Upvotes: 3

recursive
recursive

Reputation: 86144

It is normally a bitwise or operator. In this context, it's used on an enum with the flags attribute set.

Upvotes: 11

cbz
cbz

Reputation: 1764

It's a bitwise OR of two values, presumably it creates a FileAccessRule with both FullAccess and Modify permissions set.

Upvotes: 3

Related Questions