Thursday, October 21, 2010

C# 4.0–New Feature: Enums, Flags and HasFlag

C# 4.0 adds a new instance method called “HasFlag” on Enum types.

This is a convenience methods that allows you to check if a flag (bit) has been set on an enum value.

eg:

The System.IO.FileAccess enum is defined as follows:

[Serializable, ComVisible(true), Flags]
public enum FileAccess
{
   Read = 1,
   ReadWrite = 3,
   Write = 2
}

Code:

FileAccess fileAccessMode = FileAccess.Read;

if (fileAccessMode.HasFlag(FileAccess.Write))
{
   ……………
}

if (fileAccessMode.HasFlag(FileAccess.Read))
{
   ……………
}

the above code basically translates to:

if ( (fileAccessMode & FileAccess.Write) == FileAccess.Write)
{
   ……………
}

if ( (fileAccessMode & FileAccess.Read) == FileAccess.Read)
{
   ……………
}

MSDN: http://msdn.microsoft.com/en-us/library/system.enum.hasflag.aspx

No comments: