C#
enums
attribute
programming
duplicate

Get Enum from Description attribute

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In C#, an enum member can carry a DescriptionAttribute to expose a human-readable label. Going from enum value to description is straightforward; going the other direction requires reflection, because the description is metadata attached to the enum field.

Define the enum with descriptions

A typical enum looks like this:

csharp
1using System.ComponentModel;
2
3public enum OrderStatus
4{
5    [Description("Waiting for payment")]
6    PendingPayment,
7
8    [Description("Ready to ship")]
9    ReadyToShip,
10
11    [Description("Sent to customer")]
12    Shipped
13}

If a user selects "Ready to ship" from a UI, your code may need to convert that description back into OrderStatus.ReadyToShip.

Read the enum from the description

The core approach is:

  1. iterate over enum values
  2. inspect the corresponding field
  3. read the DescriptionAttribute
  4. compare its text with the input
csharp
1using System;
2using System.ComponentModel;
3using System.Linq;
4using System.Reflection;
5
6public static class EnumHelper
7{
8    public static T FromDescription<T>(string description) where T : struct, Enum
9    {
10        foreach (var value in Enum.GetValues(typeof(T)).Cast<T>())
11        {
12            FieldInfo field = typeof(T).GetField(value.ToString())!;
13            var attribute = field.GetCustomAttribute<DescriptionAttribute>();
14
15            if (attribute != null && attribute.Description == description)
16            {
17                return value;
18            }
19
20            if (attribute == null && value.ToString() == description)
21            {
22                return value;
23            }
24        }
25
26        throw new ArgumentException(
27            $"No {typeof(T).Name} value found for description '{description}'.");
28    }
29}
30
31var status = EnumHelper.FromDescription<OrderStatus>("Ready to ship");
32Console.WriteLine(status);

This generic helper works for any enum type that uses DescriptionAttribute.

Return a safe result instead of throwing

If the input may be invalid, a Try-style API is often safer than throwing exceptions.

csharp
1using System;
2using System.ComponentModel;
3using System.Linq;
4using System.Reflection;
5
6public static class EnumHelper
7{
8    public static bool TryFromDescription<T>(string description, out T result)
9        where T : struct, Enum
10    {
11        foreach (var value in Enum.GetValues(typeof(T)).Cast<T>())
12        {
13            FieldInfo field = typeof(T).GetField(value.ToString())!;
14            var attribute = field.GetCustomAttribute<DescriptionAttribute>();
15
16            if ((attribute != null && attribute.Description == description) ||
17                (attribute == null && value.ToString() == description))
18            {
19                result = value;
20                return true;
21            }
22        }
23
24        result = default;
25        return false;
26    }
27}

That is useful for parsing user input, query strings, or imported files where failure is expected occasionally.

Cache results if the lookup is frequent

Reflection is fine for occasional lookups. If the code runs repeatedly in a hot path, cache the mapping once.

csharp
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Linq;
5using System.Reflection;
6
7public static class EnumCache<T> where T : struct, Enum
8{
9    public static readonly Dictionary<string, T> ByDescription =
10        Enum.GetValues(typeof(T))
11            .Cast<T>()
12            .ToDictionary(
13                value =>
14                {
15                    var field = typeof(T).GetField(value.ToString())!;
16                    var attribute = field.GetCustomAttribute<DescriptionAttribute>();
17                    return attribute?.Description ?? value.ToString();
18                },
19                value => value);
20}

Then a lookup becomes:

csharp
var status = EnumCache<OrderStatus>.ByDescription["Sent to customer"];

This is much faster when the same mapping is used many times.

Description strings versus stable identifiers

Be careful about using descriptions as a system-level identifier. Description text is often meant for display and may change for wording or localization reasons.

Use description-based parsing when:

  • the enum is tightly tied to one display language
  • the mapping is local and controlled
  • users or configs truly use the description text

If the value must stay stable across versions and languages, a dedicated code string is often a better design than relying on display-oriented descriptions.

Common Pitfalls

The biggest mistake is assuming Enum.Parse can read the description text automatically. It cannot. Enum.Parse works with enum names, not with DescriptionAttribute.

Another issue is forgetting that some enum members may not have a DescriptionAttribute. A robust helper should decide whether to ignore those members or fall back to the enum name.

Developers also overlook performance. Reflection is perfectly fine for occasional parsing, but repeated lookups should usually be cached.

Finally, description text can change over time. If external systems depend on it, a wording change can break parsing unexpectedly. Use stable identifiers when long-term compatibility matters.

Summary

  • Converting from DescriptionAttribute back to an enum requires reflection.
  • A generic helper can inspect enum fields and compare description text safely.
  • 'TryFromDescription is often better than throwing for user-driven input.'
  • Cache the mapping if the lookup happens frequently.
  • Do not treat human-facing description text as a stable integration contract unless that tradeoff is deliberate.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.