Table of Contents

Enum

Extensions and attributes for enriching enums with metadata, enabling conversion between enum keys, custom text and custom values — with full support in JSON serialization.

Features

  • EnumTextAttribute for display-friendly enum names
  • EnumValueAttribute for machine-readable values
  • ToText() to convert enum to text
  • ToValue() to convert enum to custom value
  • GetEnumText() to retrieve the attribute value without fallback
  • GetEnumValue() to retrieve the attribute value without fallback
  • ToEnum() to convert strings back to enum values
  • IsAny() to check whether an enum value matches any value in a set
  • EnumExtensions<TEnum> for generic enum helpers
  • ASP.NET model binding support
  • JSON serialization/deserialization support

Behavior

ToEnum() matching priority:

  1. Direct key name match (case insensitive)
  2. EnumValue attribute match (case insensitive)
  3. EnumText attribute match (case insensitive)
  4. Returns first key in enum (default) if no match

ToValue() strips leading underscore from keys formatted as _0something — allowing numeric-prefixed enum keys that are invalid in C# without the underscore prefix.

JSON serialization via string.Json() respects both EnumValue and EnumText attributes during deserialization and serialization.

TypeDescriptor — all ASP.NET model binding automatically uses EnumValue and EnumText attribute matching when converting strings to enums, including query strings, form posts and route values.

Caveats

  • GetEnumText() and GetEnumValue() return null if attribute is not present — use ToText() / ToValue() if you want a fallback to key name
  • EnumExtensions<T> uses static methods instead of extension methods due to C# generic type constraints
Tip

Use EnumValue for machine-readable identifiers (IDs, codes, symbols) and EnumText for human-readable display strings — they serve different purposes and can both be applied to the same key.

Examples

public enum Status
{
    [EnumText("Open")]
    Open,

    [EnumValue("in_progress")]
    InProgress,

    [EnumText("Closed")]
    [EnumValue("closed")]
    Closed
}

Status.Open.ToText();             // "Open"
Status.InProgress.ToValue();      // "in_progress"
Status.InProgress.GetEnumValue(); // "in_progress"
Status.Closed.GetEnumText();      // "Closed"

ASP.NET model binding

public IActionResult Get([FromQuery] Status status)
{
    return Ok(status);
}

Requests with query params such as these bind correctly:

?status=Open
?status=in_progress
?status=Closed

JSON serialization

var json = new { status = Status.InProgress }.Json();

This serializes using the configured enum value instead of the raw numeric underlying enum value.

Example with numeric-like enum names

public enum Codes
{
    _0,
    _1,
    _2A
}
Codes._1.ToValue(); // "1"

Generic enum helpers

var keys = EnumExtensions<Color>.GetKeys();
var values = EnumExtensions<Color>.GetValues();
var enums = EnumExtensions<Color>.GetEnums();