Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 577
Jason Avatar asked Jun 23 '26 17:06

Jason


1 Answers

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

  • Using Attributes with Enums
  • Enum With String Values In C#

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).

like image 151
Roman Avatar answered Jun 26 '26 10:06

Roman