Of Enum, FlagsAttribute and Enum.Parse

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

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

Foo f = Foo.Foo | Foo.Bar | Foo.Quux;

this results in:


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:

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?

Application Name WilderBlog Environment Name Production
Application Ver Runtime Framework .NETCoreApp,Version=v1.1
App Path D:\home\site\wwwroot Runtime Version .NET Core 4.6.24628.01
Operating System Microsoft Windows 6.2.9200 Runtime Arch X86