Skip to content

.Net Enum Values As Bit Flags

Every now and then I find myself needing to set multiple values to an enum object and test this later on, synonymously I usually find myself also scouring the net on the best practice on how to set, access and test these enum flags :)

So today I thought I would post a definitive reference I found on the net..

Specify flag-annotated enum:

[Flags]
public enum Column
{
None = 0,
Priority = 1 << 0,
Customer = 1 << 1,
Contract = 1 << 2,
Description = 1 << 3,
Tech = 1 << 4,
Created = 1 << 5,
Scheduled = 1 << 6,
DueDate = 1 << 7,
All = int.MaxValue
};

The [Flags] attribute allows you to do this:

Column MyColumns = Column.Customer | Column.Contract;

To check if contains flag:

if ((MyColumns & Column.Customer) != 0)

To check if has flag or higher:

if (MyColumns >= Column.Customer)

To check if has flag or lower:

if (MyColumns <= Column.Customer)

To set a flag:

MyColumns |= Column.Tech;

To clear a flag:

MyColumns &= ~Column.Tech;

To toggle (flip) a flag:

MyColumns ^= Column.Contract;

To clear all flags:

MyColumns = Column.None;

To set all flags:

MyColumns = Column.All;

To set all flags EXCEPT one or more:

MyColumns = Column.All ^ Column.Tech ^ Column.Status;

Credit to Jeremy Lundy for the comprehensive write up.

VN:F [1.9.10_1130]
Rating: 4.7/5 (13 votes cast)
VN:F [1.9.10_1130]
Rating: +4 (from 6 votes)
.Net Enum Values As Bit Flags, 4.7 out of 5 based on 13 ratings
Bookmark and Share
kick it on DotNetKicks.com
Shout it

NOW, FOR A WORD FROM OUR SPONSORS

One Comment

  1. Great article! Applies to many languages.

    VA:F [1.9.10_1130]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.10_1130]
    Rating: 0 (from 0 votes)
    Posted on 17-May-10 at 6:11 pm | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*

My name is Graham O'Neale and I'm a software architect from Gold Coast, Australia. I am an overtime thinker, full time coder and awake part time in the real world. I have a keen interest in software development, particularly in the realm of programming (C#, ASP.NET, ASP.NET MVC, LINQ (2 SQL), Entity Framework, Silverlight, Blend, WCF, WPF) and a keen interest in the cutting edge and innovation. I have a new found love for design patterns, ALT.NET practices and well crafted software architecture. The purpose of this blog is to express any thoughts, findings, tips and gripes along my travels in the wonderful world of coding and technology...