7

I'm trying to enhance my enum so I've tried a suggestion on Display and another one on Description.

I'm annoyed because I don't understand the difference between them. Both Description class and Display class are from framework 4.5.

It's additionally annoying since neither of them work in the code. I'm testing the following but I only get to see the donkeys...

[Flags]
public enum Donkeys
{
  [Display(Name = "Monkey 1")]
  Donkey1 = 0,
  [Description("Monkey 2")]
  Donkey2 = 1
}
Community
  • 1
  • 1
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

1 Answers1

3

Neither of these attributes have any effect on the enum's ToString() method, which is what gets called if you just try to insert it into a Razor template. ToString() always uses the name declared in code -- Donkey1 and Donkey2 in your case. To my knowledge, there's no built-in way to specify an alternate string representation for the enum to use automatically.

I assume there are (at least) two reasons for that:

  1. Serialization. ToString() uses the name so that Enum.Parse() can parse it back into the enum.
  2. Localization. .NET was designed with global audiences firmly in mind, and if you want a human-readable string representation of an enum, it's extremely unlikely that there will be just one string representation, at which point it's going to be up to your application to figure out how to do it.

If you know your app will never be translated to other languages, or if you just want a string representation you can use in debug output, you're welcome to use an attribute (either one from the Framework, or one you declare yourself) to define a string representation for each enum value, and write some utility functions to do the string conversion. But you can't make the enum's ToString() do it for you (since that would break serialization); you'd have to write your own code to do it.

However, since you're writing a Web app, there's a fair chance that you will have a global audience -- in which case you'll need to localize your enum strings the same way you localize all your other text.

Joe White
  • 94,807
  • 60
  • 220
  • 330
  • So the approach I'll principally have to use is the *switch* as shown in [this question](http://stackoverflow.com/questions/23062683/custom-names-on-enum-elements/23062820?noredirect=1#comment35252224_23062820)? Any better suggestion? – Konrad Viltersten Apr 15 '14 at 12:22