A base class for quickly and easily creating strongly typed enum replacements in C#.
A base class for quickly and easily creating strongly typed enum replacements in C#.
If you like or are using this project please give it a star. Thanks!
An implementation of a type-safe object-oriented alternative to C# enum.
Thanks to Scott DePouw, Antão Almada, and Nagasudhir Pulla for help with this project!
The framework is provided as a set of NuGet packages. In many cases you'll only need the base package, but if you need serialization and/or ORM support there are many implementation-specific packages available to assist.
To install the minimum requirements:
Install-Package Ardalis.SmartEnumTo install support for serialization, AutoFixture, EF Core, Model Binding, or Dapper select the lines that apply:
Install-Package Ardalis.SmartEnum.AutoFixture
Install-Package Ardalis.SmartEnum.JsonNet
Install-Package Ardalis.SmartEnum.SystemTextJson
Install-Package Ardalis.SmartEnum.Utf8Json
Install-Package Ardalis.SmartEnum.MessagePack
Install-Package Ardalis.SmartEnum.ProtoBufNet
Install-Package Ardalis.SmartEnum.EFCore
Install-Package Ardalis.SmartEnum.ModelBinding
Install-Package Ardalis.SmartEnum.DapperThe latest version of the package supports .NET 8 and NetStandard 2.0.
Define your smart enum by inheriting from SmartEnum<TEnum> where TEnum is the type you're declaring. For example:
using Ardalis.SmartEnum;
public sealed class TestEnum : SmartEnum<TestEnum>
{
public static readonly TestEnum One = new TestEnum(nameof(One), 1);
public static readonly TestEnum Two = new TestEnum(nameof(Two), 2);
public static readonly TestEnum Three = new TestEnum(nameof(Three), 3);
private TestEnum(string name, int value) : base(name, value)
{
}
}The default value type is int but it can be set using the second generic argument TValue.
The string alias can also be set explicitly, where spaces are allowed.
using Ardalis.SmartEnum;
public sealed class TestEnum : SmartEnum<TestEnum, ushort>
{
public static readonly TestEnum One = new TestEnum("A string!", 1);
public static readonly TestEnum Two = new TestEnum("Another string!", 2);
public static readonly TestEnum Three = new TestEnum("Yet another string!", 3);
private TestEnum(string name, ushort value) : base(name, value)
{
}
}Just like regular enum, more than one string can be assigned to the same value but only one value can be assigned to a string:
using Ardalis.SmartEnum;
public sealed class TestEnum : SmartEnum<TestEnum>
{
public static readonly TestEnum One = new TestEnum(nameof(One), 1);
public static readonly TestEnum Two = new TestEnum(nameof(Two), 2);
public static readonly TestEnum Three = new TestEnum(nameof(Three), 3);
public static readonly TestEnum AnotherThree = new TestEnum(nameof(AnotherThree), 3);
// public static TestEnum Three = new TestEnum(nameof(Three), 4); -> throws exception
private TestEnum(string name, int value) : base(name, value)
{
}
}In this case, TestEnum.FromValue(3) will return the first instance found, either TestEnum.Three or TestEnum.AnotherThree. No order should be assumed.
The Value content is used when comparing two smart enums, while Name is ignored:
TestEnum.One.Equals(TestEnum.One); // returns true
TestEnum.One.Equals(TestEnum.Three); // returns false
TestEnum.Three.Equals(TestEnum.AnotherThree); // returns trueInheritance can be used to add "behavior" to a smart enum.
This example adds a BonusSize property, avoiding the use of the switch typically used with regular enums:
…You can take this a step further and use the ManagerType and associated BonusSize property in a parent class like so:
public class Manager
{
private ManagerType _managerType { get; set; }
public string Type
{
get => _managerType.Name;
set
{
if (!ManagerType.TryFromName(value, true, out var parsed))
{
throw new Exception($"Invalid manager type of '{value}'");
}
_managerType = parsed;
}
}
public string BonusSize
{
get => _managerType.BonusSize();
set => _bonusSize_ = value;
}
}This other example implements a state machine. The method CanTransitionTo() returns true if it's allowed to transition from current state to next; otherwise returns false.
…You can list all of the available options using the enum's static List property:
foreach (var option in TestEnum.List)
Console.WriteLine(option.Name);List returns an IReadOnlyCollection so you can use the Count property to efficiently get the number of available options.
var count = TestEnum.List.Count;Access an instance of an enum by matching a string to its Name property:
var myEnum = TestEnum.FromName("One");Exception SmartEnumNotFoundException is thrown when name is not found. Alternatively, you can use TryFromName that returns false when name is not found:
if (TestEnum.TryFromName("One", out var myEnum))
{
// use myEnum here
}Both methods have a ignoreCase parameter (the default is case sensitive).
Access an instance of an enum by matching its value:
var myEnum = TestEnum.FromValue(1);Exception SmartEnumNotFoundException is thrown when value is not found. Alternatively, you can use TryFromValue that returns false when value is not found:
if (TestEnum.TryFromValue(1, out var myEnum))
{
// use myEnum here
}Display an enum using the ToString() override:
Console.WriteLine(TestEnum.One); // OneGiven an instance of a TestEnum, switch depending on value:
switch(testEnumVar.Name)
{
case nameof(TestEnum.One):
...
break;
case nameof(TestEnum.Two):
...
break;
case nameof(TestEnum.Three):
...
break;
default:
...
break;
}Using pattern matching:
switch(testEnumVar)
{
case null:
...
break;
case var e when e.Equals(TestEnum.One):
...
break;
case var e when e.Equals(TestEnum.Two):
...
break;
case var e when e.Equals(TestEnum.Three):
...
break;
default:
...
break;
}Because of the limitations of pattern matching SmartEnum also provides a fluent interface to help create clean code:
testEnumVar
.When(TestEnum.One).Then(() => ... )
.When(TestEnum.Two).Then(() => ... )
.When(TestEnum.Three).Then(() => ... )
.Default( ... );N.B. For performance critical code the fluent interface carries some overhead that you may wish to avoid. See the available benchmarks code for your use case.
Support has been added for a Flag functionality.
This feature is similar to the behaviour seen when applying the [Flag] attribute to Enums in the .NET Framework
All methods available on the SmartFlagEnum class return an IEnumerable<SmartFlagEnum> with one or more values depending on the value provided/method called.
Some Functionality is shared with the original SmartEnum class, listed below are the variations.
When setting the values for a SmartFlagEnum It is imperative to provide values as powers of two. If at least one value is not set as power of two or two or more power of two values are provided inconsecutively (eg: 1, 2, no four!, 8) a SmartFlagEnumDoesNotContainPowerOfTwoValuesException will be thrown.
…This behaviour can be disabled by applying the AllowUnsafeFlagEnumValuesAttribute to the smart enum class. Note: If power of two values are not provided the SmarFlagEnum will not behave as expected!
…Combination values can be provided explicitly and will be returned in place of the multiple flag values that would have been returned from the FromValue() method.
…These explicit values can be provided above the highest allowable flag value without consequence, however attempting to access a value that is higher than the maximum flag value that has not explicitly been provided (for example 4) will cause a SmartEnumNotFoundException to be thrown.
…A Negative One (-1) value may be provided as an All value. When a value of -1 is passed into any of the FromValue() methods an IEnumerable containing all values (excluding 0) will be returned.
If an explicit Combination value exists with a value of -1 this will be returned instead.
……Access an IEnumerable of enum instances by matching a string containing one or more enum names seperated by commas to its Names property:
var myFlagEnums = TestFlagEnum.FromName("One, Two");Exception SmartEnumNotFoundException is thrown when no names are found. Alternatively, you can use TryFromName that returns false when no names are found:
if (TestFlagEnum.TryFromName("One, Two", out var myFlaNo open issues yet, or sync has not completed.