🏠 VisualStudioTutor.com  ·  C# Tutorial Home  ·  C# Lesson 18 of 40
Lesson 18 of 40 Core C# Intermediate ⏱ 35 min

Enums, Attributes & Reflection

Represent fixed states with enums, attach metadata with custom attributes, and inspect that metadata at runtime with reflection.

Part 1: What You Will Learn

Represent fixed states with enums, attach metadata with custom attributes, and inspect that metadata at runtime with reflection.

  • Use an enum instead of magic numbers or repeated status strings.
  • Create a custom attribute that stores display metadata.
  • Apply attributes to enum members.
  • Use reflection to read an attribute from the selected enum value.

Project setup: Create a .NET 10 Console App. No additional NuGet package is required.

Part 2: Topic-Specific Working Example

The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.

using System.Reflection;

public enum OrderStatus
{
    [DisplayName("Waiting for payment")]
    Pending,

    [DisplayName("Ready to ship")]
    Paid,

    [DisplayName("Delivered to customer")]
    Delivered
}

[AttributeUsage(AttributeTargets.Field)]
public sealed class DisplayNameAttribute(string text) : Attribute
{
    public string Text { get; } = text;
}

static string GetDisplayName(OrderStatus status)
{
    FieldInfo field = typeof(OrderStatus).GetField(status.ToString())!;

    DisplayNameAttribute? attribute =
        field.GetCustomAttribute<DisplayNameAttribute>();

    return attribute?.Text ?? status.ToString();
}

OrderStatus current = OrderStatus.Paid;

Console.WriteLine($"Raw enum value: {current}");
Console.WriteLine($"Display text: {GetDisplayName(current)}");

Part 3: How the Code Works

  • `OrderStatus` restricts the status to a known set of values.
  • `DisplayNameAttribute` derives from `Attribute`, so it can be attached to program metadata.
  • `typeof(OrderStatus).GetField(...)` obtains the reflected field representing the selected enum member.
  • `GetCustomAttribute<T>()` reads the attribute and lets the program use its metadata at runtime.

Part 4: Mini Project & Practice

Mini project: create a SupportTicketPriority enum with Low, Normal, High, and Critical values. Give each member a custom Description attribute and display the description selected by the user.

Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.

When you are comfortable with this lesson, continue to Lesson 19.

C# in Visual Studio 2026

📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition