Shawn Wildermuth's Rants and Raves

Thanks for visiting my blog! See more about me here: About Me

Of Enum, FlagsAttribute and Enum.Parse
Of Enum, FlagsAttribute and Enum.Parse
August 5, 2005

I found it very interesting in a little test that the Flags attribute doesn’t seem to change the way that the CLR numbers Enumerations.  So that this enumeration:

public enum UnFoo {   Foo,   Bar,   Quux,   Foobar } 

this code ends up not working as i’d expect:

Foo f = Foo.Foo | Foo.Bar | Foo.Quux; Console.WriteLine(f.ToString());

this results in:

Foobar

This happens because Foo = 0, Bar = 1, Quux = 2, Foobar = 3, and Foo | Bar | Quux | Foobar = 3. So if you use a [Flags], make sure and number the enum properly:

[Flags] public enum Foo {   Foo = 1,   Bar = 2,   Quux = 4,   Foobar = 8 }

Another interesting thing is that I like that Enum.ToString() and Enum.Parse() do the right thing with Flaged enumerations:

Foo f = Foo.Foo | Foo.Bar | Foo.Quux; Foo pf = (Foo) Enum.Parse(typeof(Foo), f.ToString()); if (f == pf) Console.WriteLine("They equal!");

It’s cool that when you -OR- flagged numerations together that the Enum.ToString() turns it into a common delimited list. How cool is that?