Smart Enum in C#

Amr elshaer
2 min readDec 9, 2021

--

Let’s implement our example without smart enum first:-

There are a few problems with enumerations like this:

  • Behavior related to the enumeration gets scattered around the application
  • New enumeration values require shotgun surgery
  • Enumerations don’t follow the Open-Closed Principle

Adding a new enumeration value is quite a large pain, as there are lots of these switch statements around to go back and modify. In the case above, we want the “default” behavior for defensive coding purposes, but a new enumeration value will cause an exception to be thrown.

With enumeration behavior scattered around, we can never bring it back to the source type, because enumeration types can’t have any behavior (or state for that matter).

Instead of an enumeration, I like to use an enumeration class.

We using SmartEnum Package to implement our smart enum

  • Notice I also get a much nicer display name, I can display name with spaces or any thing I want. In the past, I always had to do a lot of finagling to put spaces in the names when I displayed them.
  • The behavior can be pushed down into the enumeration class, with each specific enumeration type supplying specific behavior.
  • Enumerations work well in a variety of scenarios, but can break down quickly inside your domain model. Enumeration classes provide much of the same usability, with the added benefit of becoming a destination for behavior.
  • Switch statements are no longer necessary, as I can push that variability and knowledge where it belongs, back inside the model.

Resources:-

--

--

Amr elshaer
Amr elshaer

Written by Amr elshaer

Software engineer | .Net ,C# ,Angular, Javascript

Responses (7)