0

My enum structure is this

public enum UserRole
{
    Administrator = "Administrator",
    Simple_User = "Simple User",
    Paid_User = "Paid User"
}

Now i want to read this enum value by using its name suppose

String str = UserRole.Simple_User;

it gives me "Simple User" in str instead of "Simple_User"

How we can do this???

2
  • Why would you want Simple_User intead? If you do why not change the value in the enum? What are you trying to accomplish anyway because it may be you're trying to use an enum where you might need something else, more context is needed. Commented Jul 19, 2011 at 15:16
  • Explain, how did you compile this code and it produces unwanted result? :-) Commented Jul 19, 2011 at 15:28

5 Answers 5

3

You can do a friendly description like so:

public enum UserRole
    {
        [Description("Total administrator!!1!one")]
        Administrator = 1,

        [Description("This is a simple user")]
        Simple_User = 2,

        [Description("This is a paid user")]
        Paid_User = 3,
    }

And make a helper function:

 public static string GetDescription(Enum en)
        {
            Type type = en.GetType();

            MemberInfo[] info = type.GetMember(en.ToString());

            if (info != null && info.Length > 0)
            {
                object[] attrs = info[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }

            return en.ToString();
        }

And use it like:

string description = GetDescription(UserRole.Administrator);
Sign up to request clarification or add additional context in comments.

Comments

2

Okay so by now you know that enum really is a list of numbers that you can give a handy string handle to like:

public enum ErrorCode
{
    CTCLSM = 1,
    CTSTRPH = 2,
    FBR = 3,
    SNF = 4
}

Also, as @StriplingWarrior showed, you can go so far by getting the enum string name and replacing underscores etc. But what I think you want is a way of associating a nice human string with each value. How about this?

public enum ErrorCode
{
    [EnumDisplayName("Cataclysm")]
    CTCLSM = 1,
    [EnumDisplayName("Catastrophe")]
    CTSTRPH = 2,
    [EnumDisplayName("Fubar")]
    FBR = 3,
    [EnumDisplayName("Snafu")]
    SNF = 4
}

Okay there's probably something in System.ComponentModel that does this - let me know. The code for my solution is here:

[AttributeUsage(AttributeTargets.Field)]
public class EnumDisplayNameAttribute : System.Attribute
{
    public string DisplayName { get; set; }

    public EnumDisplayNameAttribute(string displayName)
    {
        DisplayName = displayName;
    }
}

And the funky Enum extension that makes it possible:

public static string PrettyFormat(this Enum enumValue)
{
    string text = enumValue.ToString();
    EnumDisplayNameAttribute displayName = (EnumDisplayNameAttribute)enumValue.GetType().GetField(text).GetCustomAttributes(typeof(EnumDisplayNameAttribute), false).SingleOrDefault();

    if (displayName != null)
        text = displayName.DisplayName;
    else
        text = text.PrettySpace().Capitalize(true);

    return text;
}

So to get the human-friendly value out you could just do ErrorCode.CTSTRPH.PrettyFormat()

Comments

1

Hmm, enums can't have string values. From MSDN's Enum page:

An enumeration is a set of named constants whose underlying type is any integral type except Char.


To get the string version of the enum use the Enum's ToString method.

String str = UserRole.Simple_User.ToString("F");

2 Comments

Its not working enum gives me error "Cannot implicitly convert type 'string' to 'int'" and i saw at MSDN enum is a collection of string and int combination not a string-string combination...
@Gaurav Enum's can't be strings. Your UserRole enum won't work.
0

I'm a little confused by your question, because C# doesn't allow you to declare enums backed by strings. Do you mean that you want to get "Simple User", but you're getting "Simple_User" instead?

How about:

var str = UserRole.Simple_User.ToString().Replace("_", " ");

Comments

0

You can do this by attribute, but really I think using an enum like this is possibly the wrong way to go about things.

I would create a user role interface that exposes a display name property, then implement that interface with a new class for each role, this also let's you add more behaviour in the future. Or you could use an abstract class so any generic behaviour doesn't get duplicated...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.