Table of Contents

StrictEnum for .NET / Unity

Runtime/System/StrictEnum.cs   HeaderDoc

(c) 2024 Sator Imaging, Licensed under the MIT License https://github.com/sator-imaging/Unity-Fundamentals

StrictEnum is an efficient library to reuse Enum caches stored in system library instead of creating sophisticated dictionary. And also there are allocation-free methods for Unity.

How to Use

// retrieve cached names and values
var names = StrictEnum.GetFieldNames<TEnum>();
var labels = StrictEnum.GetDisplayNames<TEnum>();
var values = StrictEnum.GetValues<TEnum>();
var numbers = StrictEnum.GetUnderlyingValues<TEnum>();           // ReadOnlySpan<ulong>
var asMemory = StrictEnum.GetUnderlyingValuesAsMemory<TEnum>();  // ReadOnlyMemory<ulong>

// get field/display name from enum value
var name = StrictEnum.ToFieldNameString<MyEnum>(val);     // or val.ToFieldNameString();
var label = StrictEnum.ToDisplayNameString<MyEnum>(val);  // or val.ToDisplayNameString();

// get enum value by field/display name. `TryGet*` methods are also available
val = StrictEnum.GetValueByFieldName<MyEnum>(text);
val = StrictEnum.GetValueByFieldName<MyEnum>(text, StringComparison.OrdinalIgnoreCase);
val = StrictEnum.GetValueByDisplayName<MyEnum>(text);

// to customize display names, set factory method *before* call methods
// note that duplicate entry is not allowed except for 0 or 1 character names
StrictEnum.CustomDisplayNameFactory(enumType, (enumType, fieldName, indexAsULong) =>
{
    return StrictEnum.BeautifyFieldName(fieldName);  // builtin helper method
});

// underlying type validation
_ = StrictEnum.IsInt32(typeof(MyEnum));
_ = StrictEnum.IsInt32Convertible(typeof(MyEnum));   // enum value can be casted to int32 (eg. short, byte)
_ = StrictEnum.IsUnderlyingValueSigned(typeof(MyEnum));
_ = StrictEnum.IsOrdinalFromZero(typeof(MyEnum));    // enum value is starting from 0 and increment by 1
                                                     // i.e. can be used as array index `names[(int)enumValue]`

TODO