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
EnumTextvalue or falls back to key name as string - ToValue(): returns
EnumValuevalue or falls back to key name as string - GetEnumText(): returns
EnumTextvalue or null if attribute not present - GetEnumValue(): returns
EnumValuevalue or null if attribute not present - ToEnum(): converts string to enum key — matches key name,
EnumValueorEnumText(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 viaTypeDescriptor— ASP.NET model binding automatically usesEnumValueandEnumTextmatching for query strings, form posts and route values
Behavior
ToEnum() matching priority:
- Direct key name match (case insensitive)
EnumValueattribute match (case insensitive)EnumTextattribute match (case insensitive)- 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()andGetEnumValue()returnnullif attribute is not present — useToText()/ToValue()if you want a fallback to key nameEnumExtensions<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.