How to define an enum with string value?

You can't - enum values have to be integral values. You can either use attributes to associate a string value with each enum value, or in this case if every separator is a single character you could just use the char value:

enum Separator
{
    Comma = ',',
    Tab = '\t',
    Space = ' '
}

(EDIT: Just to clarify, you can't make char the underlying type of the enum, but you can use char constants to assign the integral value corresponding to each enum value. The underlying type of the above enum is int.)

Then an extension method if you need one:

public string ToSeparatorString(this Separator separator)
{
    // TODO: validation
    return ((char) separator).ToString();
}

You can achieve it but it will require a bit of work.

  1. Define an attribute class which will contain the string value for enum.

  2. Define an extension method which will return back the value from the attribute. Eg..GetStringValue(this Enum value) will return attribute value.

  3. Then you can define the enum like this..

    public enum Test : int {
        [StringValue("a")]
        Foo = 1,
        [StringValue("b")]
        Something = 2        
    } 
    
  4. To get back the value from Attribute Test.Foo.GetStringValue();

Refer : Enum With String Values In C#

Tags:

C#

String

Enums