Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an enum with string value?

Tags:

string

c#

enums

People also ask

Can enum have string values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

How do I assign an enum to a string?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Can enum have string value C#?

Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string. Custom Enumeration Class.


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();
}

As far as I know, you will not be allowed to assign string values to enum. What you can do is create a class with string constants in it.

public static class SeparatorChars
{
    public static String Comma { get { return ",";} } 
    public static String Tab { get { return "\t,";} } 
    public static String Space { get { return " ";} } 
}

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#


For a simple enum of string values (or any other type):

public static class MyEnumClass
{
    public const string 
        MyValue1 = "My value 1",
        MyValue2 = "My value 2";
}

Usage: string MyValue = MyEnumClass.MyValue1;


You can't do this with enums, but you can do it like that:

public static class SeparatorChars
{
    public static string Comma = ",";

    public static string Tab = "\t";

    public static string Space = " ";
}