Blog Consulting CodeHelper About

Associating enums with strings in .Net

Unfortunately, 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: Ex. 123ABC is not allowed Ex. United States of America is not allowed The Description attribute decoration is used to define a descriptive name for a given property or event. The description decoration is defined under the System.ComponentModel Namespace Unfortunately, the way to read the names of the Enum members is limited and it returns only the Enum Member name, not the description.

Prerequisites

Solution

  1. Use the Description Attribute from the System.ComponentModel Namespace
  2. use CodeHelper.Core.Extensions
  3. Call the description with the Description() method

Example

The Countries Enum

using System.ComponentModel;

public enum Countries
{
[Description("United States of America")]
UnitedStates,
[Description("Belgium, Belgie, Belgique")]
Belgium,
France,
}

The Code

using CodeHelper.Core.Extensions;
var _usaDesc = Countries.UnitedStates.Description();
var _usaString = Countries.UnitedStates.ToString();
var _usaNumber = Countries.UnitedStates;
Result United States of America UnitedStates 0

Related .Net Articles