KnowDotNet NetRefactor

System.IO and Bit Flags

by William Ryan
Print this Article Discuss in Forums

Every time I write or use System.IO I like it more and more.  And the more I use this namespace, the more I realize how other parts of the FCL all work together. I'd like to use the FileAttributes Enumeration of the File class as an example.  A common practice in programming is to manipulate a file's attributes.  So let's look at an example:


File.SetAttributes(@"C:\myAssembly.dll", FileAttributes.Hidden|FileAttributes.Hidden|FileAttributes.ReadOnly);


What just happened here?  Well, I set three different file attributes (all of which can be shown visually by right clicking on the file in Windows Explorer and selecting Properties) in one statement.  Notice that there is only one comma in the call, this isn't an overload.  If I used this instead:

File.SetAttributes(@"C:\myAssembly.dll", FileAttributes.Hidden|FileAttributes.Hidden);


I would still call the exact same method.  Typically, when you want to set multiple properties of an object, you'd need to use different overloads.  However, we aren't dealing with properties, we are using Attributes.  And one of the ways that you can use attributes is via Flags or FlagAttributes.

So, in this instance, the attributes are members of the FileAttributes enumeration and behind the scenes, the declaration looks something like this:

[Flags]
public enum FileAttributtes{
    ReadOnly       = 0x0001,
    Hidden          = 0x0002,
    ....
    Encrypted      = 0x4000
}



So, if you wanted to take advantage of this what would you do?

[Flags]
public enum mySampelEnum{
      firstOption           = 1,
      secondOption          = 2,
      thirdOption           =3
}


Now, to call this using Flags, here's how you'd do it:


mySampleEnum someEnum = mySampleEnum.firstOption | mySampleEnum.secondOption | mySampleEnum.thirdOption;
Debug.WriteLine(someEnum.ToString("F"));


The Debug window would have "firstOption, secondOption, thirdOption" as its output.  However, this may seem weird, how does this all of these three options get outputted into the literal above?  Well, the "F" is a formatter that tells the compiler to output the format as flags.  Compare using this to writing three or four different properties, or only allowing your users to choose one at a time!  There possibilites are endless....

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing