Part 1 – Introduction
Enumeration or Enum types are an integral part of C# language. They have been around since the inception of language. Unfortunately, the Enum types also have some limitations. Enum types are not object-oriented. When we have to use Enums for control flow statements, behavior around Enums gets scattered across the application. We cannot inherit or extend the Enum types. These issues can especially be a deal-breaker in Domain-Driven Design (DDD).
Enumeration classes help get around the limitations of Enum types. The concept of Enumeration classes is not new. There are some excellent materials available around how we can use Enumeration classes in Domain-Driven Design (DDD). This post will be a multi-part series where I would not only demo some advantages of Enumeration classes over traditional Enum types but also discuss how we can use these classes beyond DDD.
Here is an example of the Enumeration class. The eShopOnContainers example on GitHub inspires this code. I have made some minor adjustments and added a couple of methods.
Let us consider we have a traditional Enum PaymentType as below.
Now, consider PaymentType also has some behavior around the enum values. With the Enum types, this behavior can be added only outside of PaymentType with ugly control statements such as this.
We can convert PaymentType Enum to an Enumeration class as below:
The PaymentType now is just a regular class. That allows us to further enhance the Enumeration class by adding new behavior within the PaymentType class.
As you can see in the above code, with Enumeration classes, we can get rid of switch statements and move the implementation details within PaymentType. In the DDD world, it means that the behavior does not leak outside our domain model anymore. The usage of PaymentType is the same as before, making it easier to refactor code and replace the existing Enum type to Enumeration.
Enumeration classes provide a great alternative to Enum types. They can be especially useful in DDD by preventing the behavior leaking outside of the domain model. In my subsequent posts, I would discuss how we can take this concept further.