Repository navigation
OnixLabs.Core.Enumeration
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
public abstract partial class Enumeration<T> :
IEquatable<T>,
IComparable<T>,
IComparable
where T : Enumeration<T>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.
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, andName. - Ordering compares
Valuefirst, then falls back to an ordinal comparison ofName.
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.
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)
{
}
}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)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| Constructor | Description |
|---|---|
Enumeration(int, string) |
Initializes a new instance of the Enumeration<T> class. Protected; called from a derived type's constructor. |
Initializes a new instance of the Enumeration<T> class.
protected Enumeration(int value, string name)| 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. |
| Exception | Condition |
|---|---|
ArgumentException |
name is null, empty, or consists only of whitespace. |
| Property | Type | Description |
|---|---|---|
Name |
string |
Gets the name of the enumeration entry. |
Value |
int |
Gets the value of the enumeration entry. |
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; }Gets the integer value associated with the current enumeration entry.
public int Value { get; }| 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. |
| 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. |
Gets the enumeration entry with the specified name.
public static T FromName(string name)| Parameter | Type | Description |
|---|---|---|
name |
string |
The name of the enumeration entry. |
Returns the single entry whose Name equals name.
| Exception | Condition |
|---|---|
ArgumentException |
No entry, or more than one entry, exists for name. |
Gets the enumeration entry with the specified value.
public static T FromValue(int value)| Parameter | Type | Description |
|---|---|---|
value |
int |
The value of the enumeration entry. |
Returns the single entry whose Value equals value.
| Exception | Condition |
|---|---|
ArgumentException |
No entry, or more than one entry, exists for value. |
Gets all the enumeration entries declared by the current type.
public static IReadOnlySet<T> GetAll()Returns a read-only set of all entries. The set is cached per concrete type.
Gets all the enumeration entries, as value/name tuples, for the current type.
public static IReadOnlySet<(int Value, string Name)> GetEntries()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.
Gets all the enumeration names for the current type.
public static IReadOnlySet<string> GetNames()Returns a read-only set of entry names. The set is cached per concrete type, and the same instance is returned on every call.
Gets all the enumeration values for the current type.
public static IReadOnlySet<int> GetValues()Returns a read-only set of entry values. The set is cached per concrete type, and the same instance is returned on every call.
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 a signed integer indicating the relative order of the entries.
Compares the current entry with another object. Behaves as CompareTo(T?) when obj is an instance of T.
public int CompareTo(object? obj)Returns a signed integer indicating the relative order of the objects.
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 true if the entries are equal; otherwise, false.
Determines whether the current entry is equal to another object.
public override bool Equals(object? obj)Returns true if obj is an equal entry of type T; otherwise, false.
Returns a hash code for the current entry, combining its runtime type, Name, and Value.
public override int GetHashCode()Returns a 32-bit signed integer hash code.
Obtains a ValueTuple<int, string> that represents the current enumeration entry.
public (int Value, string Name) ToEntry()Returns a (int Value, string Name) tuple representing this entry.
Returns the Name of the current enumeration entry.
public override string ToString()Returns the value of Name.
| Operator | Description |
|---|---|
operator == |
Determines whether two entries are equal. |
operator != |
Determines whether two entries are not equal. |
Performs an equality comparison between two instances.
public static bool operator ==(Enumeration<T>? left, Enumeration<T>? right)Returns true if left is equal to right; otherwise, false. Two null references are considered equal.
Performs an inequality comparison between two instances.
public static bool operator !=(Enumeration<T>? left, Enumeration<T>? right)Returns true if left is not equal to right; otherwise, false.
ONIXLabs .NET Library · Repository · NuGet · License (Apache-2.0)
Copyright © ONIXLabs 2020. Licensed under the Apache License, Version 2.0.
- Enumeration<T>
- Optional<T>
- OptionalEqualityComparer<T>
- OptionalExtensions
- Result
- Result<T>
- ResultEqualityComparer<T>
- ResultExtensions
- Specification<T>
- Preconditions
- IValueEquatable<T>
- IValueComparable<T>
- IBinaryConvertible
- ISpanBinaryConvertible
- IMemoryBinaryConvertible
- ArrayExtensions
- ComparableExtensions
- DateTimeExtensions
- ISpanParsableExtensions
- ObjectExtensions
- RandomExtensions
- ReadOnlySequenceExtensions
- ReadOnlySpanExtensions
- StringExtensions
- Base16
- Base32
- Base58
- Base64
- IBaseCodec
- IBaseValue
- IBaseValue<T>
- Base16Codec
- Base32Codec
- Base58Codec
- Base64Codec
- Base16FormatProvider
- Base32FormatProvider
- Base58FormatProvider
- Base64FormatProvider
- EncodingExtensions
- ReadOnlySpanExtensions
- StringBuilderExtensions
- BigDecimal
- BigDecimalEqualityComparer
- BigDecimalOrdinalityComparer
- NumberInfo
- NumberInfoEqualityComparer
- NumberInfoOrdinalityComparer
- Int256
- Int512
- UInt256
- UInt512
- Float128
- Float256
- GenericMath
- NumericsExtensions
- ConversionMode
- ScaleMode
- Hash
- NamedHash
- Sha3
- Sha3Hash224
- Sha3Hash256
- Sha3Hash384
- Sha3Hash512
- Sha3Shake128
- Sha3Shake256
- MerkleTree
- MerkleTree<T>
- PrivateKey
- PublicKey
- NamedPrivateKey
- NamedPublicKey
- EcdhPrivateKey
- EcdhPublicKey
- EcdsaPrivateKey
- EcdsaPublicKey
- EddsaPrivateKey
- EddsaPublicKey
- RsaPrivateKey
- RsaPublicKey
- DigitalSignature
- DigitalSignatureAndPublicKey
- Salt
- Secret
- ICryptoPrimitive<T>
- IHashable
- IEcdhPrivateKey
- IEcdsaPrivateKey
- IEddsaPrivateKey
- IRsaPrivateKey
- IPrivateKeyDerivable<T>
- IPrivateKeyExportable
- IPrivateKeyImportable<T>
- IPrivateKeyPemImportable<T>
- IPrivateKeyPkcs8Exportable
- IPrivateKeyPkcs8Importable<T>
- IPrivateKeyPkcs8PemExportable
- IPrivateKeyRawExportable
- IPrivateKeyRawImportable<T>
- IPrivateKeyRawPemExportable
- IEcdhPublicKey
- IEcdsaPublicKey
- IEddsaPublicKey
- IRsaPublicKey
- IPublicKeyExportable
- IPublicKeyImportable<T>
- IPublicKeyPemExportable
- IPublicKeyPemImportable<T>
- IPublicKeyRawExportable
- IPublicKeyRawImportable<T>
- HashAlgorithmExtensions
- ReadOnlySpanExtensions