Enumerations and String values in ASP.NET

I'm looking for some best practice advice on enumerations and retrieving an associated string value. Given this:

public enum Fruits {
    Apple,
    Orange,
    Grapefruit,
    Melon
}

What is the best way to get a related string value of the name? Eg. "Grapefruit", given that the string value may not match the representation in the enumeration. eg "Casaba Melon"

My current thinking is function accepting an enum and returning a string, but would that not mean hard coding the string values (which I prefer not to do)? Is using a resources file where the string can be retrieved via the enumeration too heavy handed?

Answers


To answer your question, you can decorate your enums with attributes to give them proper display string. Here are some examples

The main limitation of this approach is if you ever need to internationalize your application, I don't know of a way to make attribute strings change value based on thread locale (or whatever way you use to distinguish locales).


R0MANARMY has already given a very nice solution. I'll provide this alternative, less nice, one though still. You can probably make this culture sensitive easier.

Say you have the enum

public enum NicePeople
{
    SomeGuy,
    SomeOtherGuy
}

You can then make an extension method like this

public static class MyExtensions
{
    public static string GetName(this NicePeople tst)
    {
        switch (tst)
        {
            case NicePeople.SomeGuy:
                return "Some Nice guy";
            case NicePeople.SomeOtherGuy:
                return "Another Nice Guy";
            default:
                throw new Exception("Naw");
        }
    }
}

And get your serial killers name like this

NicePeople.SomeGuy.GetName()

Need Your Help

Setting/retrieving mode in Slim Framework V3

php configuration slim slim-3

I am new to Slim Framework (PHP). I was going through tutorials and testing some code and tried the following:

New column issue after association

c# sql database ado.net

I created 2 tables in Visual studio say TA and TB. In edmx file I made 1-to-many association between TA and TB. After making association, a new column is generated in TB named TAId.