6

I have declared enum as below

public enum State
    {
        KARNATAKA = 1,
        GUJRAT = 2,
        ASSAM = 3,
        MAHARASHTRA = 4,
        GOA = 5
    }

From external sources, I get the State values as either 1 or 2 or 3 or 4 or 5.

Based on the value i get, I need to look up this enum and get its string.

For Ex: If the input value is 1, I need to return KARNATAKA as string. Similarly, If the input value is 5, I need to return GOA as string.

Is there a easy way to get the string with out using CASE or IFELSE.

Vikas Kunte
  • 683
  • 4
  • 15
  • 35
  • You mean like [this](https://msdn.microsoft.com/en-us/library/system.enum.getname(v=vs.110).aspx)? – Icepickle May 20 '18 at 10:36
  • 2
    `state.ToString()` for exam: `int i = 1; State st = (State)i; string name=st.ToString();` name will get `KARATAKA` ? – Aria May 20 '18 at 10:41
  • @Aria if your code is not obfuscated, yes you will get like that. but it is not preferred way. (and also if you code is going to be released, code obfuscation is good way to go) – Amit May 20 '18 at 10:57
  • @Amit, Yes but he did't talk about `obfuscating`, as simple text he want "if the input value is 1, I need to return KARNATAKA as string." – Aria May 20 '18 at 10:58
  • look at this link I think you ask for that [get string from enum](https://stackoverflow.com/questions/309333/enum-string-name-from-value?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – Mohamed Salah May 20 '18 at 10:58
  • @MohamedSalah, Like my first comment . – Aria May 20 '18 at 10:59
  • @Aria and what will you do if state name should have space too in it? Description Tag is best suitable solution of this requirement. – Amit May 20 '18 at 11:53
  • What about Enum.GetName(typeof(yourEnum), yourValue); https://learn.microsoft.com/en-us/dotnet/api/system.enum.getname?view=net-6.0 – leguminator Oct 14 '22 at 14:47

3 Answers3

19

You can simply use the nameof expression to get the name of an enum, enum value, property, method, classname, etc.

The fastest, compile time solution using nameof expression.

Returns the literal of the enum.

public enum MyEnum {
    CSV,
    Excel
}

// calling code
string enumAsString = nameof(MyEnum.CSV) // enumAsString = "CSV"
Reap
  • 1,047
  • 13
  • 16
8

you can add Description tags to your enum like below

public enum State
{
    [Description("Karnataka")]
    KARNATAKA = 1,
    [Description("Gujarat")]
    GUJRAT = 2,
    [Description("Assam")]
    ASSAM = 3,
    [Description("Maharashtra")]
    MAHARASHTRA = 4,
    [Description("Goa")]
    GOA = 5
}

And then get assigned Desription string from enum like below

State stateVal = State.GOA;
string stateName = GetEnumDescription(stateVal);

if you have state as in number as you have mentioned comments, you can still easily cast it to enum type.

int stateVal = 2;
string stateName = GetEnumDescription((State)stateVal);   

GetEnumDescription() which returns string for name of Enumerations.

public static string GetEnumDescription(Enum enumVal)
{
    System.Reflection.MemberInfo[] memInfo = enumVal.GetType().GetMember(enumVal.ToString());
    DescriptionAttribute attribute = CustomAttributeExtensions.GetCustomAttribute<DescriptionAttribute>(memInfo[0]);
    return attribute.Description;
}

NOTE

As operation on enum is less costly than string operations, string value of enum should be limited to display purpose only, while internally you must use enum itself in logic.

The way to get string value of enum is more preferred. As if you have used enum at lot of places in your code, and you need to change text on display, you will have to change text at one place only.

For example,

Suppose you have used this enum throughout your project and then you realize that your spelling of Gujarat is wrong, if you change the text of enum it self you need to change it through whole code (thankfully visual studio makes it little easier) while if you use Description as label to be display you will only need to change that only.

Or

when you Space in name (which you have to display).

EG. "Jammu and Kashmir" is another state of India.

you can have abbreviation (here "JK") in enum name and complete string with space in description.

Amit
  • 1,821
  • 1
  • 17
  • 30
  • 1
    You should use `GetCustomAttribute()` if you only want one attribute, which also does the typecasting. Also instead of `object enumVal` you should restrict the signature to enum values by using `Enum enumVal`. Also if you restrict the type to `State` why don’t you just write `State enumVal`. If you want to support all kinds of enums it should be `Type type = enumVal.GetType();`. – ckuri May 20 '18 at 14:15
  • @ckuri Thanks for pointing that out, I will update that once I get on my computer. – Amit May 20 '18 at 15:35
4

I know this is an old question, but you can write an extension class/method specific to enumerations that will get the text value. This is based off of the above approach, however, it eliminates a boiler-plate code being wrapped around enums and simplifies the code required to get these names.

The benefit to this approach is that you can use this extension directly from the enum value much like using nameof(MyEnum.Value1), or you can use it on a property of an object which wouldn't work using the nameof(...) approach.

Here is the extension code:

    public static class EnumerationExtensions
    {
        public static string AsText<T>(this T value) where T : Enum
        {
            return Enum.GetName(typeof(T), value);
        }
    }

Usage:

enum MyEnum {
  Value1,
  Value2,
}

class MyObject {
  MyEnum enumValue;
}


//Output directly from an Enum value
Console.WriteLine(MyEnum.Value1.AsText());  //Output: Value1

//Output from a property that is an enumeration
//NOTE: nameof(obj.enumValue) would not provide the desired value. but the AsText() method will give the name of the property value.
new obj = new MyObject { enumValue = MyEnum.Value2 };
Console.WriteLine(obj.enumValue.AsText());  //Output: Value2 

Bug Maker
  • 434
  • 7
  • 20
RLH
  • 15,230
  • 22
  • 98
  • 182
  • 1
    Useful! But there's a typo in the return statement. Shoud be "return Enum.GetName(typeof(T), value);" – selganor Mar 10 '23 at 14:27