Enum.HasFlag – where have you been all my life?

August 24, 2010

one comment

If you’ve ever used enumerations in .NET with bitwise operations, using the Flags attribute, you should be familiar with the following piece of code:

enum Permission
  None = 0,
  Read = 1,
  Edit = 2,
  Delete = 4,
  ChangePermission = 8,
  FullControl = Read | Edit | Delete | ChangePermission
Permission permission = Permission.Read | Permission.Edit;
if ((permission & Permission.Delete) == Permission.Delete)
  Console.WriteLine("Has permissions");

In .NET 4, a new method was introduced in order to relieve yourself from this ugly code – Enum.HasFlag. So instead of writing the above if statement, you can write it like so:

if (permission.HasFlag(Permission.Delete))
  Console.WriteLine("Has permissions");

This method makes the code readable, simpler, and saves you time explaining to new developers what is a bitwise operation.

How the hell did I miss this method in the “what’s new in .NET 4” documentation … better late than never.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


one comment

  1. ShlomoAugust 24, 2010 ב 3:02 pm

    מדהים – תודה רבה