Refactor enum->class: Answer 1

This is the follow up to the enum->class refactoring post.


So, one approach is to try to decode what ‘enum’ does in C#.  Thomas Eyre’s answer is pretty much the same, with a couple differences:

·         Thomas wrote his TDD, and delivered it with tests.  Good for you!

·         I mark the field as ‘readonly’.  It’s a little safer, a little clearer about my intentions, and possibly better optimized by JIT.

·         Mine is a ‘struct’.  That’s a good choice just because enum is a value type.  It also means that I don’t have to override the equality operations.


Here’s the result of my attempt:


      struct E


            public const int a = 0;

            public const int b = 1;

            public const int c = 2;


            public readonly int Value;

            public E(int value) { this.Value = value; }


            public static implicit operator int(E e) { return e.Value; }

            public static implicit operator E(int i) { return new E(i); }



I guess it’s not terribly exciting, but it does seem to work pretty well.


Can you see any differences between this struct and an actual enum?

Comments (0)

Skip to main content