NuGet: Ardalis.SmartEnum
A simple package with a base Smart Enum class.
Thanks for Scott Depouw for his help with this!
Define your smart enum by inheriting from SmartEnum<TEnum, TValue>
where TEnum
is the type you're declaring and TValue
is the type of its value (typically int
). For example:
public class TestEnum : SmartEnum<TestEnum, int>
{
public static TestEnum One = new TestEnum(nameof(One), 1);
public static TestEnum Two = new TestEnum(nameof(Two), 2);
public static TestEnum Three = new TestEnum(nameof(Three), 3);
protected TestEnum(string name, int value) : base(name, value)
{
}
}
You can list all of the available options using the enum's static List
property:
var allOptions = TestEnum.List;
Access an instance of an enum by matching a string to its Name
property:
var myEnum = TestEnum.FromString("One");
Access an instance of an enum by matching its value:
var myEnum = TestEnum.FromValue(1);
Display an enum using the ToString()
override:
Console.WriteLine(TestEnum.One); // One (1)