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
*/
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!