Richard77
Richard77

Reputation: 21631

Different way of testing 2 conditions in the same if block?

I just saw this code

if ((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
  //...
}

It seems a little weird. A different way of testing?? I'd expect easily expect something like

if ((FirstName=="Richard") & (LastName == "DeFortune" )
{
  //...
}

With the & in the middle of both tests

Thanks

Upvotes: 0

Views: 82

Answers (3)

Alok
Alok

Reputation: 274

The & mentioned here is a bitwise and-operator not a logical and (&&).

Upvotes: 0

dotnetstep
dotnetstep

Reputation: 17485

If you look at closely FileAttribute is Enum with Attribute Mark as Flag.

you will get more info at here : http://dotnetstep.blogspot.com/2009/01/flags-attribute-for-enum.html

Now single '&' is bitwise operator.

Example

        // Get file Info
        System.IO.FileInfo info = new System.IO.FileInfo("C:\\TESTTT.txt");
        // Get attribute and convert into int for better understanding 
        int val = (int)info.Attributes;
        // In my case it is 33 whoes binary value for 8 bit   00100001.

        // now we perform bitwise end with readonly FileAttributes.ReadOly is 1
        // 00100001 & 00000001 = 00000001
        int isReadOlny = val & (int)System.IO.FileAttributes.ReadOnly;
        Console.WriteLine("IsReadOnly : " + isReadOlny.ToString());

        // 00100001 & 00010000 = 00000000
        int isDirectory = val & (int)System.IO.FileAttributes.Directory;
        Console.WriteLine("IsDirectory : " + isDirectory.ToString());

        Console.WriteLine(val);
        Console.ReadLine();

Hope this help you.

Upvotes: 1

SLaks
SLaks

Reputation: 887453

That's a bitwise operator.

It checks whether fsi.Attributes has the FileAttributes.Directory bit set.

Upvotes: 1

Related Questions