Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this C# operator work in this code snippet?

I found this code snippet on SO (sorry I don't have the link to the question/answer combo)

 bool isDir = (File.GetAttributes(source) & FileAttributes.Directory) == FileAttributes.Directory;

This confuses me because FileAttributes.Directory is on both sides of the ==.

What does the & do in this case? I'm not sure how to read this line of code. I'm trying to evaluate whether a path string is a file or a directory.

like image 369
quakkels Avatar asked Jan 19 '11 22:01

quakkels


3 Answers

It is using a bit mask to test if a single bit (FileAttributes.Directory) is set.

The values of the enum are powers of two, corresponding to individual bits.

    ReadOnly = 1,
    Hidden = 2,
    System = 4,
    Directory = 16,
    Archive = 32,
    Device = 64,

If ReadOnly and Directory are set then FileAttributes is equal to 17. The calculation looks like this in binary:

File.GetAttributes(source) = 00001001   
FileAttributes.Directory   = 00001000 &
-------------------------------------
                             00001000

If the Directory bit was not set you'd get zero instead:

File.GetAttributes(source) = 00000001   
FileAttributes.Directory   = 00001000 &
-------------------------------------
                             00000000

A slightly more concise way to write the expression that gives the same effect is to test against zero:

bool isDir = (File.GetAttributes(source) & FileAttributes.Directory) != 0;
like image 98
Mark Byers Avatar answered Oct 13 '22 11:10

Mark Byers


its doing a Bitwise AND operation. Attributes are stored as bit flags, so it is and'ing those flags together with AttributeFlags.Directory to see if one of the attributes is .Directory.

Good example of Bit Flags here: http://weblogs.asp.net/wim/archive/2004/04/07/109095.aspx

[Flags]
public enum FileAttributes
{
  Archive,        // 0000
  Compressed,     // 0001
  Device,         // 0010
  Directory,      // 0100
  Encrypted,       // 1000
  ...
}

Then:

 File.GetAttributes(source):  1101
 FileAttributes.Directory:    0100
 (Logical AND):               0100

0100 is the same as the directory flag, so we now know that that flag is in the chosen flags of the enum.

like image 5
Chris Kooken Avatar answered Oct 13 '22 13:10

Chris Kooken


It is the logical & operator. In this particular example it checks if the FileAttributes enumeration has the Directory value, verifying if the string pointed by the source variable is a directory.

like image 2
Darin Dimitrov Avatar answered Oct 13 '22 13:10

Darin Dimitrov