Files
prefab-page-detail/Prefab.Base/PrefabEnum.cs
2025-10-27 17:39:18 -04:00

58 lines
2.4 KiB
C#

namespace Prefab.Base;
/// <summary>
/// Base type for rich enumerations that behave like enums but support additional metadata and behavior.
/// </summary>
/// <typeparam name="TEnum">Concrete enumeration type deriving from <see cref="PrefabEnum{TEnum}"/>.</typeparam>
public abstract class PrefabEnum<TEnum> where TEnum : PrefabEnum<TEnum>
{
private static readonly List<TEnum> Instances = [];
/// <summary>
/// Gets the canonical name of the enumeration value.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the integral value associated with the enumeration value.
/// </summary>
public int Value { get; }
/// <summary>
/// Initializes a new enumeration value and registers it in the global instance list.
/// </summary>
/// <param name="name">Logical name exposed to consumers.</param>
/// <param name="value">Numeric identifier for persistence.</param>
protected PrefabEnum(string name, int value)
{
Name = name;
Value = value;
Instances.Add(this as TEnum ?? throw new InvalidOperationException("PrefabEnum must be instantiated with a derived type."));
}
/// <summary>
/// Gets all declared enumeration values for <typeparamref name="TEnum"/>.
/// </summary>
public static IReadOnlyList<TEnum> List => Instances;
/// <summary>
/// Resolves an enumeration value by its logical name.
/// </summary>
/// <param name="name">The name to match.</param>
/// <returns>The matching enumeration.</returns>
/// <exception cref="ArgumentException">Thrown when no enumeration value matches the supplied name.</exception>
public static TEnum FromName(string name) =>
Instances.FirstOrDefault(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
?? throw new ArgumentException($"Invalid name: {name}", nameof(name));
/// <summary>
/// Resolves an enumeration value by its integral value.
/// </summary>
/// <param name="value">The integer value to match.</param>
/// <returns>The matching enumeration.</returns>
/// <exception cref="ArgumentException">Thrown when no enumeration value matches the supplied value.</exception>
public static TEnum FromValue(int value) =>
Instances.FirstOrDefault(x => x.Value == value)
?? throw new ArgumentException($"Invalid value: {value}", nameof(value));
}