How do I override ToString in C# enums?
- by scraimer
In the post Enum ToString, a method is described to use the custom attribute DescriptionAttribute like this:
Enum HowNice {
[Description("Really Nice")]
ReallyNice,
[Description("Kinda Nice")]
SortOfNice,
[Description("Not Nice At All")]
NotNice
}
And then, you call a function GetDescription, using syntax like:
GetDescription<HowNice>(NotNice); // Returns "Not Nice At All"
But that doesn't really help me when I want to simply populate a ComboBox with the values of an enum, since I cannot force the ComboBox to call GetDescription.
What I want has the following requirements:
Reading (HowNice)myComboBox.selectedItem will return the selected value as the enum value.
The user should see the user-friendly display strings, and not just the name of the enumeration values. So instead of seeing "NotNice", the user would see "Not Nice At All".
Hopefully, the solution will require minimal code changes to existing enumerations.
Obviously, I could implement a new class for each enum that I create, and override its ToString(), but that's a lot of work for each enum, and I'd rather avoid that.
Any ideas?
Heck, I'll even throw in a hug as a bounty :-)