Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Display and Description attribute

Tags:

c#

enums

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
}
like image 491
Konrad Viltersten Avatar asked Apr 15 '14 11:04

Konrad Viltersten


1 Answers

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.

like image 155
Joe White Avatar answered Oct 26 '22 04:10

Joe White