BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 3.5+

Using Enum.HasFlag

Prior to version 3.5 of the .NET framework, extracting individual flags from an enumeration required the use of logical bitwise operators. In .NET 3.5, the need for logical operations is removed with the introduction of the Enum.HasFlag method.

Extracting Enumeration Flags

Enumerations that represent bit fields are often decorated with the Flags attribute and populated with constants that have values that are powers of two. This allows those flags to be combined in all possible permutations without individual Boolean values conflicting.

In .NET 3.0 and earlier versions, you would use logical bitwise operations to extract the value, either true or false, of one of the flags in an enumeration. The following example, which uses the FileAttributes enumeration from the System.IO namespace, obtains the value of the ReadOnly flag using the AND logical operation. When the AND executes, all bits except the one that represents read-only files are zeroed. This gives a result of zero if the flag is false, and the underlying integer value of the ReadOnly constant if the flag is true. The equality operator performs a comparison to see which of these values is present.

FileAttributes attributes
    = FileAttributes.Compressed
    | FileAttributes.ReadOnly;

bool isReadOnly =
    (attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;  // true

The process of extracting a flag from an enumeration is simplified in .NET 3.5 with the Enum class's HasFlag method. This method can be more readable than the AND operation and the comparison. It accepts a single parameter, which must be one of the constants defined in the enumeration that it is executed against. If the given flag is set, the method returns true. If not, it returns false.

The previous example can therefore be recreated as follows:

bool isReadOnly = attributes.HasFlag(FileAttributes.ReadOnly);
13 July 2012