Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

SmartEnum

> 设计协作
Open source

A base class for quickly and easily creating strongly typed enum replacements in C#.

2.4K stars0 likes2 views
WebsiteGitHub

About

A base class for quickly and easily creating strongly typed enum replacements in C#.

Table Of Contents

  • Table Of Contents
    • Sub-packages
    • Give a Star! ⭐
  • SmartEnum
    • Contributors
  • Install
    • Version
  • Usage
    • List
    • FromName()
    • FromValue()
    • ToString()
    • Switch
    • SmartFlagEnum
    • Setting SmartFlagEnum Values
    • Usage - (SmartFlagEnum)
    • FromName()
    • FromValue()
    • FromValueToString()
    • BitWiseOrOperator
    • Persisting with EF Core 2.1 or higher
    • Using SmartEnum.EFCore
    • AutoFixture support
    • Json support
    • Dapper support
    • DapperSmartEnum
    • Case Insensitive String Enum
    • Name Validation Attribute
    • Examples in the Real World
    • References

Sub-packages

SmartEnum.AutoFixture:

SmartEnum.Dapper:

SmartEnum.EFCore:

SmartEnum.JsonNet:

SmartEnum.MessagePack:

SmartEnum.ProtoBufNet:

SmartEnum.SystemTextJson:

SmartEnum.Utf8Json:

Give a Star! :star:

If you like or are using this project please give it a star. Thanks!

Smart Enum

An implementation of a type-safe object-oriented alternative to C# enum.

Contributors

Thanks to Scott DePouw, Antão Almada, and Nagasudhir Pulla for help with this project!

Install

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.SmartEnum

To 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.Dapper

Version

The latest version of the package supports .NET 8 and NetStandard 2.0.

Usage

Define your smart enum by inheriting from SmartEnum<TEnum> where TEnum is the type you're declaring. For example:

csharp
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.

csharp
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:

csharp
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:

csharp
TestEnum.One.Equals(TestEnum.One); // returns true
TestEnum.One.Equals(TestEnum.Three); // returns false
TestEnum.Three.Equals(TestEnum.AnotherThree); // returns true

Inheritance 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:

csharp
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.

…

List

You can list all of the available options using the enum's static List property:

csharp
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.

csharp
var count = TestEnum.List.Count;

FromName()

Access an instance of an enum by matching a string to its Name property:

csharp
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:

csharp
if (TestEnum.TryFromName("One", out var myEnum))
{
    // use myEnum here
}

Both methods have a ignoreCase parameter (the default is case sensitive).

FromValue()

Access an instance of an enum by matching its value:

csharp
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:

csharp
if (TestEnum.TryFromValue(1, out var myEnum))
{
    // use myEnum here
}

ToString()

Display an enum using the ToString() override:

csharp
Console.WriteLine(TestEnum.One); // One

Switch

Given an instance of a TestEnum, switch depending on value:

csharp
switch(testEnumVar.Name)
{
    case nameof(TestEnum.One):
        ...
        break;
    case nameof(TestEnum.Two):
        ...
        break;
    case nameof(TestEnum.Three):
        ...
        break;
    default:
        ...
        break;
}

Using pattern matching:

csharp
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:

csharp
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.

SmartFlagEnum

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.

Setting SmartFlagEnum Values

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.

…

Usage - (SmartFlagEnum)

…

FromName()

Access an IEnumerable of enum instances by matching a string containing one or more enum names seperated by commas to its Names property:

csharp
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:

csharp
if (TestFlagEnum.TryFromName("One, Two", out var myFla

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#cleancsharpddddesign-patterns

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category设计协作
PricingOpen source

> Related tools

F
Figma
协作式界面设计工具
S
sketch-wakatime
Sketch plugin for automatic time tracking and metrics generated from your Sketch usage.
Q
QuickColor
Quickly apply fills from the global or document color palettes to selected elements - 🎨