Make use of Enums – Clean Code Post 3

It is better to make use of an Enum than to use hardcoded strings in your code. I have heard the use of hardcoded strings be referred to as Stringly Typed rather than Strongly Typed. Using an Enum would make your code Strongly Typed.

Here is an example of some bad Stringly Typed code:

if (customerType == "Premier")
{
                
}

Here is an example of how you can improve this code by making use of an Enum called CustomerType:

if (customer.Type == CustomerType.Premier)
{
               
}

The code to define the CustomerType Enum is below.

public enum CustomerType
{
   Standard, Elevated, Premier
}

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. In the CustomerType enumeration above, Standard is 0, Elevated is 1 and Premier is 2. If you wanted to assign different values you can do something like the code below:

public enum CustomerType
{
   Standard = 100, 
   Elevated = 200, 
   Premier = 300
}

If you want to retrieve the integral value from an Enum you can use the code below:

   var customerType = (int)customer.Type;

Leave a comment