Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set string in Enum C#?

Tags:

c#

.net

enums

I want to create string ENUM in c#.

Basically i wan't to set form name in Enum. When i open form in main page that time i want to switch case for form name and open that particular form. I know ENUM allows only integer but i want to set it to string. Any Idea?

like image 996
Manoj Savalia Avatar asked Nov 28 '22 06:11

Manoj Savalia


2 Answers

Enum cannot be string but you can attach attribute and than you can read the value of enum as below....................

public enum States
{
    [Description("New Mexico")]
    NewMexico,
    [Description("New York")]
    NewYork,
    [Description("South Carolina")]
    SouthCarolina
}


public static string GetEnumDescription(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}

here is good article if you want to go through it : Associating Strings with enums in C#

like image 177
Pranay Rana Avatar answered Dec 05 '22 11:12

Pranay Rana


As everyone mentioned, enums can't be strings (or anything else except integers) in C#. I'm guessing you come from Java? It would be nice if .NET had this feature, where enums can be any type.

The way I usually circumvent this is using a static class:

public static class MyValues
{
    public static string ValueA { get { return "A"; } }
    public static string ValueB { get { return "B"; } }
}

With this technique, you can also use any type. You can call it just like you would use enums:

if (value == MyValues.ValueA) 
{
    // do something
}
like image 25
Peter Avatar answered Dec 05 '22 09:12

Peter