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?

Shawn Wildermuth
Author, Teacher, and Coach

My Courses

Building a Web App with ASP.NET Core, MVC6, EF Core, Bootstrap and Angular (updated for 2.0)
Using Visual Studio Code for ASP.NET Core Projects (new)
Implementing and Securing an API with ASP.NET Core
Building a Web App with ASP.NET Core, MVC6, EF Core and AngularJS
Building a Web App with ASP.NET5, MVC6, EF7, and AngularJS (Retired)
Best Practices in ASP.NET: Entities, Validation, and View Models
Webstorm Fundamentals
Front-End Web Development Quick Start
Lessons from Real World .NET Code Reviews
Node.js for .NET Developers

Application Name WilderBlog Environment Name Production
Application Ver Runtime Framework .NETCoreApp,Version=v2.0
App Path D:\home\site\wwwroot\ Runtime Version .NET Core 4.6.26020.03
Operating System Microsoft Windows 10.0.14393 Runtime Arch X86