Refactor enum->class

Every so often, I see a C# user say they’d like to add a method to an enum. Maybe it’s [Flags] and they want to verify that the combination of flags is legal according to their business rules. Or maybe they’re in the process of moving to something more OO, involving inheritance instead of constants.

Anyway, I’ve been trying to think about how to do it. I don’t know yet if there’s anything really compelling here, I’m still exploring.

The idea is a simple code transformation that gets you out of an enum and into a class, as simply as possible.

In my experiments, I’m starting with this blob of code. The challenge is to refactor it so that ‘E’ is not an enum, while maintaining basically the same semantics as when you started.

 

      enum E

      {

            a, b, c

      }

      class Program

      {

            void F(E e)

            {

                  E e2 = E.a;

                  switch (e)

                  {

                        case E.a:

                              break;

                        case E.b:

                              break;

                        case E.c:

                              break;

                  }

                  if (e == E.a)

                  {

                        return;

                  }

            }

      }

 

BTW, TheoY and I chatted about this today while I made tea, which is part of inspiration behind writing this entry.

 

Edit: I want you to post your ideas about how you might refactor this. Duh me for not saying so earlier!