More often than not, I try to have an enum
but for strings: in this post, I show you how to create String Enums in NET6 and C# but it is straightforward to use it in another version of the framework.
What is an enum?
Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain.
For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.). The main objective of enum
is to define our own data types (Enumerated Data Types). Enumeration is declared using enum
keyword directly inside a namespace, class, or structure.
Consider the below code for the enum. Here enum with name month
is created and its data members are the name of months like jan, feb, mar, apr, may. Now let’s try to print the default integer values of these enums. An explicit cast is required to convert from enum
type to an integral type.
public enum Cards
{
Club,
Diamond,
Heart,
Spade
}
Sometimes, you can add Description
as annotation and then use a function to give the text (see my NuGet package PSC.Extensions where I have few functions for it).
Then, if you want to define a variable with this enum
, you use it like this
Cards myCard = Cards.Club;
So, it is easy to assign a correct value. The problem is there is not native enum
for strings. So, I found a nice workaround.
Implement a String Enum
First, I want to have something like the real enum
that I can easily use as a type. Then, I want to access the values in a similar way.
So, I implemented for my ChartJs Blazor Component, the following solution:
public class Align
{
private Align(string value) { Value = value; }
public string Value { get; private set; }
public static Align Start { get { return new Align("start"); } }
public static Align Center { get { return new Align("center"); } }
public static Align End { get { return new Align("end"); } }
}
If you want to use it, it is like an enum
. The only difference is that you have to call Value
to know the exact value. For example:
Align align = Align.Start;
var value = align.Value;
I think we can cope with it. The advantage is to access easily to the values and easy to maintain.
Wrap up
In conclusion, this is how to create String Enums in C#. Please give me your feedback below or in the Forum.