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
EnumTextAttributefor display-friendly enum namesEnumValueAttributefor machine-readable valuesToText()to convert enum to textToValue()to convert enum to custom valueGetEnumText()to retrieve the attribute value without fallbackGetEnumValue()to retrieve the attribute value without fallbackToEnum()to convert strings back to enum valuesIsAny()to check whether an enum value matches any value in a setEnumExtensions<TEnum>for generic enum helpers- ASP.NET model binding support
- JSON serialization/deserialization support
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.
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();