Associating enums with strings in .NetUnfortunately, the way to read the names of the Enum members is limited and it returns only the Enum Member name, not the description.
Enums are by nature a user-defined value type to represent a list of name integers There are also some constraints on how you can name the enumeration members Name of enumeration members can not:
- be prefixed with the type name because type information is expected to be provided by development tools.
- Be a numeric value, or even starting with a number
- Have spaces in the name.
- Contains non-alphabet characters (and limited to the English Language)
System.ComponentModel NamespaceUnfortunately, the way to read the names of the Enum members is limited and it returns only the Enum Member name, not the description.
- Use the
Description Attributefrom the System.ComponentModel Namespace
- Call the description with the
The Countries Enum
public enum Countries
[Description("United States of America")]
[Description("Belgium, Belgie, Belgique")]
Result United States of America UnitedStates 0using CodeHelper.Core.Extensions;
var _usaDesc = Countries.UnitedStates.Description();
var _usaString = Countries.UnitedStates.ToString();
var _usaNumber = Countries.UnitedStates;