DEV Community

Frederik Van Lierde
Frederik Van Lierde

Posted on

3 1

Associating enums with strings in .Net

Enums are by nature a user-defind value type to represent a list of name integers

There are also some constraints 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 Ex. 123ABC is not allowed
  • Have spaces in the name. Ex. United States of Amercia is not allowed
  • Contains non-alphabet characters (and limited the the English Language)

The Description attribute decoration is used to define a descriptive name for a give property or event.

The description decoration is defined under the System.ComponentModel Namespace

Unfortuantly, the way to read the names of the Enum members is limited and it return only the Enum Member name, not the description.

Prerequisits

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,       
    }

Enter fullscreen mode Exit fullscreen mode

The Code

using CodeHelper.Core.Extensions;
var _usaDesc = Countries.UnitedStates.Description();
var _usaString = Countries.UnitedStates.ToString();
var _usaNumber = Countries.UnitedStates;
Enter fullscreen mode Exit fullscreen mode

Result
United States of America
UnitedStates
0

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more