10

I have declared an 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 example: 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 a string.

Is there an easy way to get the string without using CASE or IFELSE?

9
  • You mean like this? Commented May 20, 2018 at 10:36
  • 3
    state.ToString() for exam: int i = 1; State st = (State)i; string name=st.ToString(); name will get KARATAKA ? Commented May 20, 2018 at 10:41
  • 1
    @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) Commented May 20, 2018 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." Commented May 20, 2018 at 10:58
  • 1
    look at this link I think you ask for that get string from enum Commented May 20, 2018 at 10:58

4 Answers 4

29

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"
Sign up to request clarification or add additional context in comments.

Comments

9

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 a Description string from an enum like below:

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

If you have state as in a number as you have mentioned in comments, you can still easily cast it to an 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 an operation on an enum is less costly than string operations, the string value of enum should be limited to display purposes only, while internally you must use the enum itself in logic.

The way to get the string value of an enum is more preferred. As if you have used enum at a lot of places in your code, and you need to change the text on a display, you will have to change the 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 itself, you need to change it through whole code (thankfully, Visual Studio makes it a little easier) while if you use Description as a label to be displayed, you will only need to change that only.

Or

when you have a space in the name (which you have to display).

For example, "Jammu and Kashmir" is another state of India.

You can have an abbreviation (here "JK") in an enum name and complete the string with a space in the description.

2 Comments

You should use GetCustomAttribute<DescriptionAttribute>() 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 Thanks for pointing that out, I will update that once I get on my computer.
5

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 boilerplate 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

1 Comment

Useful! But there's a typo in the return statement. Shoud be "return Enum.GetName(typeof(T), value);"
1

Here ise better solution

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

public static T AsEnum<T>(this int value) where T : Enum
{
    if (Enum.IsDefined(typeof(T), value))
    {
        return (T)Enum.ToObject(typeof(T), value);
    }
    else
    {
        throw new ArgumentException($"{value} is not a valid value for enum {typeof(T).Name}");
    }
}
public static int AsInt<T>(this T value) where T : Enum
{
    return (int)(object)value;
}

1 Comment

But why is it a better solution? Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.