Fast, customizable, and extendable enums for C# with a clean API.
$ dotnet add package CodeChops.MagicEnumsCustomizable, and extendable enums for C# with a clean API.
Check out CodeChops projects for more projects.
// Implicit values
public record Level : MagicEnum<Level>
{
public static readonly Level Low = CreateMember(); // 0
public static readonly Level Medium = CreateMember(); // 1
public static readonly Level High = CreateMember(); // 2
}
// Explicit values
public record StarRating : MagicEnum<StarRating>
{
public static readonly StarRating One = CreateMember(1);
public static readonly StarRating Two = CreateMember();
public static readonly StarRating Three = CreateMember();
public static readonly StarRating Four = CreateMember();
public static readonly StarRating Five = CreateMember();
}
public record Vehicle(int WheelCount) : MagicEnum<Vehicle>
{
public static readonly Type.Bicycle Bicycle = CreateMember<Type.Bicycle>();
public static readonly Type.MotorCycle MotorCycle = CreateMember<Type.MotorCycle>();
public static readonly Type.Car FuelCar = CreateMember<Type.Car>(() => new(EmitsCo2: true));
public static readonly Type.Car ElectricCar = CreateMember<Type.Car>(() => new(EmitsCo2: false));
public static class Type
{
public record Bicycle() : Vehicle(WheelCount: 2);
public record MotorCycle() : Vehicle(WheelCount: 2);
public record Car(bool EmitsCo2) : Vehicle(WheelCount: 4);
}
}
Besides the default .NET enum behaviour, MagicEnums offer more features than the default .NET enum implementation:
decimal)ToString. For extra optimization, see optimization.Terminology:
- An
enumhas one or multiple members.- Each
memberhas anameand avalue.- The type of the value depends on the chosen
enum type, see: enum types.
Magic enums behave like the default .NET enum implementation:
int as default for the member value.Flag enums are supported.CodeChops.MagicEnums.CodeChops.MagicEnums.static readonly members that call CreateMember().| Method | Description |
|---|---|
CreateMember* | Creates a new enum member and returns it. |
GetEnumerator | Gets an enumerator over the enum members. |
GetMembers | Gets an enumerable over: - All enum members, or - Members of a specific value: Throws when no member has been found. |
GetValues | Gets an enumerable over the member values. |
TryGetMembers | Tries to get member(s) by value. |
TryGetSingleMember | Tries to get a single member by name / value. Throws when multiple members of the same value have been found. |
GetSingleMember | Gets a single member by name / value. Throws when not found or multiple members have been found. |
GetUniqueValueCount | Gets the unique member value count. |
GetMemberCount | Gets the member count. |
GetDefaultValue | Gets the default value of the enum. |
GetOrCreateMember* | Creates a member or gets one if a member already exists. |
The methods are
public, except for the ones marked with *, they areprotected.
Number enums (default) have a numeric type as value.
MagicEnum<TSelf, TNumber>.TNumber is omitted, int will be used as type: MagicEnum<TSelf>.TNumber can be of any type that are also supported by the default .NET implementation: byte, sbyte, short, ushort, int, uint, long, or ulong.decimal is also supported./* This example shows an int enum with implicit and explicit values. */
public record StarRating : MagicEnum<StarRating>
{
public static readonly StarRating One = CreateMember(1);
public static readonly StarRating Two = CreateMember();
public static readonly StarRating Three = CreateMember();
public static readonly StarRating Four = CreateMember();
public static readonly StarRating Five = CreateMember();
}
The example creates an enum with an int as member value.
The value of the first member is explicitly defined.
Other values are being incremented automatically, because they are defined implicitly.
/* This example shows the usage of a `decimal` as member value. */
public record EurUsdRate : MagicEnum<EurUsdRate, decimal>
{
public static readonly EurUsdRate Average2021 = CreateMember(0.846m);
public static readonly EurUsdRate Average2020 = CreateMember(0.877m);
public static readonly EurUsdRate Average2019 = CreateMember(0.893m);
public static readonly EurUsdRate Average2018 = CreateMember(0.848m);
}
Flag enums are supported just like in the default .NET implementation. Implicit value declaration is also support. See the example below. Flags enums offer extra methods:
GetUniqueFlags(): Gets the unique flags of the provided value.HasFlag(): Returns true if a specific enum member contains the provided flag./* This example shows the usage of a flags enum.
Note that member 'ReadAndWrite' flags both 'Read' and 'Write'. */
public record Permission : MagicFlagsEnum<Permission>
{
public static readonly Permission None = CreateMember(); // 0
public static readonly Permission Read = CreateMember(); // 1 << 0
public static readonly Permission Write = CreateMember(); // 1 << 1
public static readonly Permission ReadAndWrite = CreateMember(Read | Write);
}
Sometimes you only need an enumeration of strings (for example: names). In this case the underlying numeric value is not important. Magic string enums helps you achieving this:
MagicStringEnum<TSelf>./* This example shows the creation of a string enum.
The value of the members are equal to the name of the members. */
using CodeChops.MagicEnums;
public record ErrorCode : MagicStringEnum<ErrorCode>
{
public static readonly ErrorCode EndpointDoesNotExist = CreateMember();
public static readonly ErrorCode InvalidParameters = CreateMember();
public static readonly ErrorCode NotAuthorized = CreateMember();
}
Custom enums can also be created. They offer a way to create an enum of any type that you prefer:
MagicCustomEnum<TSelf, TValue>.TValue should implement IEquatable and IComparable.2D-point as member value.base class / interface. Each member contains its (uninitialized) instance as value.To achieve pattern matching, you can do the following below.
var message = level.Name switch
{
nameof(Level.Low) => "The level is low.",
nameof(Level.Medium) => "The level is medium.",
nameof(Level.High) => "The level is high.",
_ => throw new UnreachableException($"This should not occur.")
};
In this example, the enum from the default usage example is used.
Another way is to define the types in an inner class and use them as the type of an enum member:
var speedingFineInEur = vehicle switch
{
Vehicle.Type.MotorCycle => 60,
Vehicle.Type.Car => 100,
_ => 0,
};
In this example, the enum from the complex usage example is used.
Generally your enum does not dynamically add members at runtime. If this is the case, the attribute DisableConcurrency can be placed on the enum. It disables concurrency and therefore optimises memory usage and speed.
Warning! Only use this attribute when you are sure that no race conditions can take place when creating / reading members.