Enum.HasFlag

In not-so-new news, I just found out about .NET 4’s Enum.HasFlag method. This nice little method makes life with flags a little bit cleaner since you can use it instead of performing a bitwise AND and compare.

[Flags]
enum Options
{
	None = 0,
	A = 1,
	B = 2,
	C = 4
}

void Main()
{
	var options = Options.A | Options.C;
	
	// old (bitwise AND and compare)
	Console.WriteLine("A:{0}", (options & Options.A) == Options.A);
	Console.WriteLine("B:{0}", (options & Options.B) == Options.B);
	Console.WriteLine("C:{0}", (options & Options.C) == Options.C);
	
	// new (HasFlag method)
	Console.WriteLine("A:{0}", options.HasFlag(Options.A));
	Console.WriteLine("B:{0}", options.HasFlag(Options.B));
	Console.WriteLine("C:{0}", options.HasFlag(Options.C));
}

/* Output:
A:True
B:False
C:True
A:True
B:False
C:True
 */
Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

One thought on “Enum.HasFlag”

  1. Many thanks for this, Adam!
    It is awesome that I came here for the unit tests and accidentally found this info!
    Just couple of days ago I was playing with TFS API and have this:
    change.ChangeType = ChangeType.SourceRename | ChangeType.Delete
    And I could not figure out why the following returns false
    (change.ChangeType == ChangeType.SourceRename )
    And the next one returns true
    (change.ChangeType & ChangeType.SourceRename) == ChangeType.SourceRename
    Now I know along with how to write it in a cleaner way.
    You made my day!

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: