Skip to content

OnixLabs.Core.Enumeration

Matthew Layton edited this page Nov 15, 2026 · 4 revisions

Enumeration<T> Class

Represents the base class for the smart enumeration pattern: a class-based alternative to a C# enum that allows each entry to carry behaviour and methods alongside its integer value and stable name.

Namespace: OnixLabs.Core

Assembly: OnixLabs.Core.dll

Inheritance: object → Enumeration<T>

Implements: IEquatable<T>, IComparable<T>, IComparable

Definition

public abstract partial class Enumeration<T> : 
    IEquatable<T>,
    IComparable<T>,
    IComparable
    where T : Enumeration<T>

Type Parameters

T

The concrete derived type.

The constraint where T : Enumeration<T> is the curiously recurring template pattern, which lets the base class expose strongly typed members (such as FromName and GetAll) that return the derived type rather than the base type.

Remarks

Enumeration<T> provides the benefits of a C# enum — a fixed, named set of values — while allowing each entry to be a full object that can hold additional data and behaviour. This makes it well suited to modelling closed domains where each value needs more than an integer, such as states in a workflow, units of measure, or strategy selectors.

Each entry is declared as a public static readonly field on the derived type. Entries are discovered automatically by reflection over the public, static, declared fields of T. The discovered set is computed once per concrete type and cached in a FrozenSet<T>, so repeated calls to the static query methods do not re-scan the type. The name and value lookups used by FromName and FromValue, and the sets returned by GetEntries, GetNames and GetValues, are also built once per concrete type, so those methods return the same shared instance on every call.

Equality and ordering are based on value semantics:

  • Two entries are equal when they have the same runtime type, Value, and Name.
  • Ordering compares Value first, then falls back to an ordinal comparison of Name.

Note

Because entries are discovered from fields declared directly on T, only fields declared on the concrete type itself are included; inherited fields are not discovered. Declare each entry as public static readonly.

Examples

Declaring a smart enumeration

The minimal pattern declares a private constructor that forwards to the base constructor, and one public static readonly field per entry. Using nameof keeps the Name in sync with the field name.

using OnixLabs.Core;

public sealed class Color : Enumeration<Color>
{
    public static readonly Color Red = new(1, nameof(Red));
    public static readonly Color Green = new(2, nameof(Green));
    public static readonly Color Blue = new(3, nameof(Blue));

    private Color(int value, string name) : base(value, name)
    {
    }
}

Looking up and enumerating entries

Color red = Color.FromName("Red");      // Red
Color green = Color.FromValue(2);       // Green

IReadOnlySet<Color> all = Color.GetAll();
IReadOnlySet<string> names = Color.GetNames();                 // { "Red", "Green", "Blue" }
IReadOnlySet<int> values = Color.GetValues();                  // { 1, 2, 3 }
IReadOnlySet<(int Value, string Name)> entries = Color.GetEntries();

Console.WriteLine(red);                  // Red   (ToString returns Name)
Console.WriteLine(red == Color.Red);     // True  (value equality)
Console.WriteLine(red.CompareTo(green)); // -1    (ordered by Value)

Carrying data and behaviour

The principal advantage over a plain enum is that each entry can carry its own state and expose behaviour.

public sealed class Planet : Enumeration<Planet>
{
    public static readonly Planet Earth = new(1, nameof(Earth), 5.976e+24, 6.37814e6);
    public static readonly Planet Mars = new(2, nameof(Mars), 6.421e+23, 3.3972e6);

    private Planet(int value, string name, double mass, double radius) : base(value, name)
    {
        Mass = mass;
        Radius = radius;
    }

    public double Mass { get; }
    public double Radius { get; }

    // Each entry exposes computed behaviour based on its own data.
    public double SurfaceGravity => 6.67300e-11 * Mass / (Radius * Radius);
}

double gravity = Planet.Earth.SurfaceGravity; // 9.802652743337129

Constructors

Constructor Description
Enumeration(int, string) Initializes a new instance of the Enumeration<T> class. Protected; called from a derived type's constructor.

Enumeration(int, string)

Initializes a new instance of the Enumeration<T> class.

protected Enumeration(int value, string name)

Parameters

Parameter Type Description
value int The value of the enumeration entry.
name string The name of the enumeration entry. Must be non-null, non-empty, and non-whitespace.

Exceptions

Exception Condition
ArgumentException name is null, empty, or consists only of whitespace.

Properties

Property Type Description
Name string Gets the name of the enumeration entry.
Value int Gets the value of the enumeration entry.

Name

Gets the name of the enumeration entry. A stable, non-null, non-empty identifier that conventionally matches the static field name (for example, nameof(Active)).

public string Name { get; }

Value

Gets the integer value associated with the current enumeration entry.

public int Value { get; }

Methods

Static Methods

Method Returns Description
FromName(string) T Gets the single entry with the specified name.
FromValue(int) T Gets the single entry with the specified value.
GetAll() IReadOnlySet<T> Gets all declared entries for the current type.
GetEntries() IReadOnlySet<(int Value, string Name)> Gets all entries as value/name tuples.
GetNames() IReadOnlySet<string> Gets all entry names.
GetValues() IReadOnlySet<int> Gets all entry values.

Instance Methods

Method Returns Description
CompareTo(T?) int Compares this entry with another entry of the same type.
CompareTo(object?) int Compares this entry with another object.
Equals(T?) bool Determines whether this entry equals another entry of the same type.
Equals(object?) bool Determines whether this entry equals another object.
GetHashCode() int Returns a hash code derived from the type, name, and value.
ToEntry() (int Value, string Name) Obtains a value/name tuple representing this entry.
ToString() string Returns the Name of this entry.

FromName(string)

Gets the enumeration entry with the specified name.

public static T FromName(string name)

Parameters

Parameter Type Description
name string The name of the enumeration entry.

Returns

Returns the single entry whose Name equals name.

Exceptions

Exception Condition
ArgumentException No entry, or more than one entry, exists for name.

FromValue(int)

Gets the enumeration entry with the specified value.

public static T FromValue(int value)

Parameters

Parameter Type Description
value int The value of the enumeration entry.

Returns

Returns the single entry whose Value equals value.

Exceptions

Exception Condition
ArgumentException No entry, or more than one entry, exists for value.

GetAll()

Gets all the enumeration entries declared by the current type.

public static IReadOnlySet<T> GetAll()

Returns

Returns a read-only set of all entries. The set is cached per concrete type.

GetEntries()

Gets all the enumeration entries, as value/name tuples, for the current type.

public static IReadOnlySet<(int Value, string Name)> GetEntries()

Returns

Returns a read-only set of (int Value, string Name) tuples. The set is cached per concrete type, and the same instance is returned on every call.

GetNames()

Gets all the enumeration names for the current type.

public static IReadOnlySet<string> GetNames()

Returns

Returns a read-only set of entry names. The set is cached per concrete type, and the same instance is returned on every call.

GetValues()

Gets all the enumeration values for the current type.

public static IReadOnlySet<int> GetValues()

Returns

Returns a read-only set of entry values. The set is cached per concrete type, and the same instance is returned on every call.

CompareTo(T?)

Compares the current entry with another entry of the same type. Compares Value first; if the values are equal, falls back to an ordinal comparison of Name. A null other sorts before the current instance (returns 1).

public int CompareTo(T? other)

Returns

Returns a signed integer indicating the relative order of the entries.

CompareTo(object?)

Compares the current entry with another object. Behaves as CompareTo(T?) when obj is an instance of T.

public int CompareTo(object? obj)

Returns

Returns a signed integer indicating the relative order of the objects.

Equals(T?)

Determines whether the current entry is equal to another entry of the same type. Two entries are equal when they share the same runtime type, Value, and Name.

public bool Equals(T? other)

Returns

Returns true if the entries are equal; otherwise, false.

Equals(object?)

Determines whether the current entry is equal to another object.

public override bool Equals(object? obj)

Returns

Returns true if obj is an equal entry of type T; otherwise, false.

GetHashCode()

Returns a hash code for the current entry, combining its runtime type, Name, and Value.

public override int GetHashCode()

Returns

Returns a 32-bit signed integer hash code.

ToEntry()

Obtains a ValueTuple<int, string> that represents the current enumeration entry.

public (int Value, string Name) ToEntry()

Returns

Returns a (int Value, string Name) tuple representing this entry.

ToString()

Returns the Name of the current enumeration entry.

public override string ToString()

Returns

Returns the value of Name.

Operators

Operator Description
operator == Determines whether two entries are equal.
operator != Determines whether two entries are not equal.

operator ==

Performs an equality comparison between two instances.

public static bool operator ==(Enumeration<T>? left, Enumeration<T>? right)

Returns

Returns true if left is equal to right; otherwise, false. Two null references are considered equal.

operator !=

Performs an inequality comparison between two instances.

public static bool operator !=(Enumeration<T>? left, Enumeration<T>? right)

Returns

Returns true if left is not equal to right; otherwise, false.

See Also

ONIXLabs .NET Library


Clone this wiki locally