String Type Enum in C#

How to use Enum as string in C#.net. If we want to use enum as constant in if condition of in switch how we can use it with c#.net.
In today's article I will show string type Enum in C#.net with a simple tutorial with an example. So first we will understand what Enum is in C#.net. Here Enum is stands for enumeration type. So, enumeration type is a value type which is defined the group of constants.  Enum is defined in C#.net with the help of keyword "Enum".

Syntax for Enum

 enum Specifier
{
    value1,
    value2,
    value3
} 
Here in above example, we are having an enum with name Specifier, and some constant defined under the enum. Here when we access this enum we will get the value same as enum value which is value1. Let's run and check the output.
 Console.WriteLine(Specifier.value1); 
In above code I am trying to contestant value of enum. Let's run the code and check the output. Ones we run the code we will get the value1.

Enum Value

As all we know we majorly use enum in condition. Now let's check the condition. 

Enum Error
In above code we can see that we are having error. It will whenever we are trying put value in condition. Now to resolve this we need to define the enum with string value. So here the most important thing that we cannot directly us the enum. As we know enum define the constant. So, for defining the string value in enum we need to use class constant. Refer the below code. 

Enum Of String Type

 public static class Specifier
{
    public const string value1 = "value1";
    public const string value2 = "value2";
    public const string value3 = "value3";
} 
In above code I have defined a class of static type and in this class, I have defined few constant, which will act as the enum value.  Now let's put the value in condition. 

String Enum Value in C#.Net

In above code we are not having condition, and we are not getting any error. Now let's run the code and check the output. 

Enum string constant

Post a Comment