A simple and flexible alternative to System.Enum
- .NET 8.0 library
- similar to System.Enum, but with underlying type string
- enum constants are associated with one or more string values
- string values may be added dynamically
- much faster than System.Enum with attributes
- simple and intuitive API
- tested
- CLS compliant
- no dependencies
Implement the pattern used in the example below to define StringEnum constants. Note that each constant is associated with one or more unique strings:
public sealed class SecurityType : StringEnum<SecurityType>
{
public static SecurityType Undefined { get; } = Create("");
public static SecurityType Cash { get; } = Create("C");
public static SecurityType Stock { get; } = Create("STK");
public static SecurityType Bond { get; } = Create("BOND", "BND");
}
Assert.Equal("C", SecurityType.Cash.ToString());
Assert.Equal(SecurityType.Cash, SecurityType.ToStringEnum("C"));
Assert.Null(SecurityType.ToStringEnum("not found"));
When a StringEnum constant is associated with more than one string, the first string represents its string value.
Assert.Equal(SecurityType.Bond, SecurityType.ToStringEnum("BOND"));
Assert.Equal(SecurityType.Bond, SecurityType.ToStringEnum("BND"));
Assert.Equal("BOND", SecurityType.Bond.ToString());
Assert.Equal(["BOND", "BND"], SecurityType.Bond.ToStrings());
After the StringEnum has been created, new constants can be added by calling Add().
SecurityType? newSecurityType = SecurityType.Add("New SecurityType");
Assert.NotNull(newSecurityType);
Assert.Equal(newSecurityType, SecurityType.ToStringEnum("New SecurityType"));
Assert.Equal("New SecurityType", newSecurityType.ToString());
Assert.Equal(
[SecurityType.Undefined, SecurityType.Cash, SecurityType.Stock, SecurityType.Bond, newSecurityType],
SecurityType.ToStringEnums());
Assert.Null(SecurityType.ToStringEnum("stk"));
SecurityType.SetStringComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(SecurityType.Stock, SecurityType.ToStringEnum("stk"));
Assert.Equal(SecurityType.Cash, "C".ToStringEnum<SecurityType>());
Assert.True(SecurityType.Cash.GetType().IsStringEnum());