Skip to content

A simple and flexible alternative to System.Enum based on strings.

License

Notifications You must be signed in to change notification settings

dshe/StringEnums

Repository files navigation

StringEnums   Build status NuGet NuGet License

A simple and flexible alternative to System.Enum

  • .NET 6.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"));

Multiple String Values

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(new[] { "BOND", "BND" }, SecurityType.Bond.ToStrings());

New Constants

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());

All Constants

Assert.Equal(
    new[] { SecurityType.Undefined, SecurityType.Cash, SecurityType.Stock, SecurityType.Bond, newSecurityType },
    SecurityType.ToStringEnums());

String Case

Assert.Null(SecurityType.ToStringEnum("stk"));

SecurityType.SetStringComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(SecurityType.Stock, SecurityType.ToStringEnum("stk"));

Extensions

Assert.Equal(SecurityType.Cash, "C".ToStringEnum<SecurityType>());

Assert.True(SecurityType.Cash.GetType().IsStringEnum());