Table of Contents

Enum

Description

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

  • EnumText attribute: attach a custom text to any enum key
  • EnumValue attribute: attach a custom value (any type) to any enum key
  • ToText(): returns EnumText value or falls back to key name as string
  • ToValue(): returns EnumValue value or falls back to key name as string
  • GetEnumText(): returns EnumText value or null if attribute not present
  • GetEnumValue(): returns EnumValue value or null if attribute not present
  • ToEnum(): converts string to enum key — matches key name, EnumValue or EnumText (case insensitive)
  • IsAny(): checks if enum matches any in a list
  • EnumExtensions<T>: static helpers to get all keys, enums or values from an enum type
  • Model binding: ToEnum() is registered globally via TypeDescriptor — ASP.NET model binding automatically uses EnumValue and EnumText matching for query strings, form posts and route values

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.