EnumStringValues 3.0.0

Enum String Values

Library to allow conversion between an Enum Value and a string, in both directions.

There is a newer version of this package available.
See the version list below for details.
Install-Package EnumStringValues -Version 3.0.0
dotnet add package EnumStringValues --version 3.0.0
<PackageReference Include="EnumStringValues" Version="3.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add EnumStringValues --version 3.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

EnumStringValues

Library to allow conversion between an Enum Value and a string, in both directions.
Implemented as an Attribute to be applied to Enum fields to define a string, and methods to extract the defined string given the enum or provide the matching given a string.
Enum name is registered as a default stringValue everywhere.

Breaking Change in latest Release (2.0 -> 3.0)

The Deprecated ParseStringValueToEnum method has been removed. Please use ParseToEnum instead.

Example Usage

/* Define Mappings. */
public enum exampleEnum
{
  EnumWithoutAnyCustomStringValue,

  [StringValue("AValue")]
  EnumWithAStringValueDefined,

  [StringValue("2", true),
   StringValue("Two")]
  EnumWithMultipleStringValuesDefinedAndOneMarkedAsPreferred
}


/* Map from Enum to string. */
using EnumStringValues.EnumExtensions;

exampleEnum.EnumWithoutAnyCustomStringValue.GetStringValue()
               // returns "EnumWithoutAnyCustomStringValue"

exampleEnum.EnumWithAStringValueDefined.GetStringValue()
               // returns "AValue"

exampleEnum.EnumWithMultipleStringValueDefinedAndOneMarkedAsPreferred.GetStringValue() 
               // returns "2"


/* Map from string to Enum. */
("EnumWithoutAnyCustomStringValue").ParseToEnum<exampleEnum>()
               // returns exampleEnum.EnumWithoutAnyCustomStringValue

("AValue").ParseToEnum<exampleEnum>()
               // returns exampleEnum.EnumWithAStringValueDefined

("2").ParseToEnum<exampleEnum>()
               // returns exampleEnum.EnumWithMultipleStringValuesDefinedAndOneMarkedAsPreferred

("Two").ParseToEnum<exampleEnum>()
               // also returns exampleEnum.EnumWithMultipleStringValuesDefinedAndOneMarkedAsPreferred

Classes, Methods, etc.

Class: StringValueAttribute

An Attribute applicable to Enum fields

Methods:

StringValueAttribute.ctor(string, bool)
        - Defines a string value to associate with an Enum, and indicates whether it
          is preferred. Second parameter may be omitted and defaults to false.

Class: EnumExtensions

A Class defining 2 groups of methods:
Extension Methods on System.Enum, and Static helper methods.

Methods
    System.Enum.GetStringValue()
        - Returns the String Value associated with an Enum.
          If more than one value is defined returns the "Preferred" string value.
          If no value is defined, returns the name of the Enum.
    System.Enum.GetAllStringValues()
        - Returns an IEnumerable of all the String Values associated with an
          Enum, irrespective of preference.
    EnumExtensions.ParseToEnum<T>(this string)
        - Takes a string and an EnumType and returns the matching Enum value.
          Throws if no match can be made.
    EnumExtensions.ParseToEnumList<T>(this IEnumerable<string>)
        - Takes a collection of strings and an EnumType and returns the matching Enum values.
          Throws if any of the strings are unmatchable.
    EnumExtensions.TryParseStringValueToEnum<T>(string, out T)
        - Mirrors the int.TryParse() pattern.
          Takes a string and an EnumType and checks for a matching Enum value.
          If one exists, populates the out param and returns true. Otherwise returns false.
    EnumExtensions.EnumerateValues<T>()
        - Helper Method that returns all of the values in an EnumType.

Removed
    EnumExtensions.ParseStringValueToEnum<T>(string)
        - This was identical to ParseToEnum, but not exposed as an extension of string, and differently named.
          If you were using it, please now use ParseToEnum.

Exceptions and Edge Cases

All the Generic methods are constrained as T: struct, IConvertible, which I believe to be as close to "is an Enum" as one can get in generic Type constraints. There is a further reflection-based check in the code, so calling any of them with T as a non-Enum will throw an InvalidOperationException.

  • Calling GetStringValue when no string value is defined
  • ...... will return enum Name
  • Calling ParseToEnum<T>() when the string is null
  • ...... will throw an ArgumentNullException
  • Calling ParseToEnum<T>() when the string doesn't match anything
  • ...... will throw an UnmatchedStringValueException()
  • Calling ParseToEnumList<T>() when any of the strings are null or don't match anything
  • ...... will throw an appropriate Exception depending on the first problem hit.
  • Calling GetStringValue when multiple values are defined but none are marked as preferred
  • ...... may return any of the string values.
  • Calling GetStringValue when multiple values are marked as preferred
  • ...... may return any of the preferred values.
  • Calling ParseToEnum<T>() when the string is defined for multiple Enums
  • ...... may return any of the Enums that it matches.

Note that in all of these 'may return any' cases, I suspect that it will always return the top-most value, but that will be dependant on .NET's implementation of various methods and is not in anyway guaranteed by this library! Frankly, any of these would be a mis-use of the library and could arguably throw instead.

If TryParseStringValueToEnum is called and fails, then it will populate the output variable to default(T), likely the first defined value of the Enum.

Rationale behind library

This library was initially constructed to allow an easy way to define the string value associated with each value of an Enumeration.
You can convert an Enum value to a string very easily, but only if the string you want is the name of that value - this library allows you to define any string and easily convert from that Enum to that string. The scenario in my case was wanting a piece of text to display to the user that wasn't forced to be CamelCase.

A natural extension of that was then to allow you to convert in the opposite direction - Given a string and an Enum Type return the enum that matches to that string. The scenario here, was reading a datafile into a program, and wanting to have one of the properties as an Enum.

Finally, it then seemed to be useful to allow you to define multiple possible strings that match to the Enum - so that it could handle the possibility that multiple different inputs should actually map to the same Enum. Once you're defining multiple strings for each enum, you then need to know which one to use when converting from enum to string, so add a property to mark one of those String Values as the 'Preferred' string value.

Version History

  • 3.0 - Convert the project to .Net Standard 2.0
    - Remove the Obsolete ParseStringValueToEnum method.

  • 2.0 - Make the library use the existing Enum name as its default string value
    - Exposed the Parse methods as extensions on String and List&lt;string&gt;
    - Added a clone of the basic Parse method renamed as ParseToEnum&lt;T&gt;
    - NOTE: The old parse method (ParseStringValueToEnum) is now deprecated and will be removed in vNext. ParseToEnum is identical and should be used instead.

  • 1.0 - Final cosmetic tweaks. (Project is now essentially complete and this is likely the last update in a while)

  • 0.11 - Update nuget files on build

  • 0.10 - Explicitly support recent major .NET versions.

  • 0.9 - Created a nuget package, so committing structure for that.

  • 0.8 - Upgrade to .NET 4.5.1

  • 0.7 - Make nuget manage the nUnit dependency.

  • 0.6 - Fix namespaces which previously related to my personal Utilities project :)

  • 0.5 - Rename Parse Methods to reflect the fact that they return Enums, not ints.

  • 0.4 - Improve Attribute constructor layout, and adjust access modifiers

  • 0.3 - Fix Null string handling.

  • 0.2 - Initial Readme.

  • 0.1 - Initial Upload.

EnumStringValues

Library to allow conversion between an Enum Value and a string, in both directions.
Implemented as an Attribute to be applied to Enum fields to define a string, and methods to extract the defined string given the enum or provide the matching given a string.
Enum name is registered as a default stringValue everywhere.

Breaking Change in latest Release (2.0 -> 3.0)

The Deprecated ParseStringValueToEnum method has been removed. Please use ParseToEnum instead.

Example Usage

/* Define Mappings. */
public enum exampleEnum
{
  EnumWithoutAnyCustomStringValue,

  [StringValue("AValue")]
  EnumWithAStringValueDefined,

  [StringValue("2", true),
   StringValue("Two")]
  EnumWithMultipleStringValuesDefinedAndOneMarkedAsPreferred
}


/* Map from Enum to string. */
using EnumStringValues.EnumExtensions;

exampleEnum.EnumWithoutAnyCustomStringValue.GetStringValue()
               // returns "EnumWithoutAnyCustomStringValue"

exampleEnum.EnumWithAStringValueDefined.GetStringValue()
               // returns "AValue"

exampleEnum.EnumWithMultipleStringValueDefinedAndOneMarkedAsPreferred.GetStringValue() 
               // returns "2"


/* Map from string to Enum. */
("EnumWithoutAnyCustomStringValue").ParseToEnum<exampleEnum>()
               // returns exampleEnum.EnumWithoutAnyCustomStringValue

("AValue").ParseToEnum<exampleEnum>()
               // returns exampleEnum.EnumWithAStringValueDefined

("2").ParseToEnum<exampleEnum>()
               // returns exampleEnum.EnumWithMultipleStringValuesDefinedAndOneMarkedAsPreferred

("Two").ParseToEnum<exampleEnum>()
               // also returns exampleEnum.EnumWithMultipleStringValuesDefinedAndOneMarkedAsPreferred

Classes, Methods, etc.

Class: StringValueAttribute

An Attribute applicable to Enum fields

Methods:

StringValueAttribute.ctor(string, bool)
        - Defines a string value to associate with an Enum, and indicates whether it
          is preferred. Second parameter may be omitted and defaults to false.

Class: EnumExtensions

A Class defining 2 groups of methods:
Extension Methods on System.Enum, and Static helper methods.

Methods
    System.Enum.GetStringValue()
        - Returns the String Value associated with an Enum.
          If more than one value is defined returns the "Preferred" string value.
          If no value is defined, returns the name of the Enum.
    System.Enum.GetAllStringValues()
        - Returns an IEnumerable of all the String Values associated with an
          Enum, irrespective of preference.
    EnumExtensions.ParseToEnum<T>(this string)
        - Takes a string and an EnumType and returns the matching Enum value.
          Throws if no match can be made.
    EnumExtensions.ParseToEnumList<T>(this IEnumerable<string>)
        - Takes a collection of strings and an EnumType and returns the matching Enum values.
          Throws if any of the strings are unmatchable.
    EnumExtensions.TryParseStringValueToEnum<T>(string, out T)
        - Mirrors the int.TryParse() pattern.
          Takes a string and an EnumType and checks for a matching Enum value.
          If one exists, populates the out param and returns true. Otherwise returns false.
    EnumExtensions.EnumerateValues<T>()
        - Helper Method that returns all of the values in an EnumType.

Removed
    EnumExtensions.ParseStringValueToEnum<T>(string)
        - This was identical to ParseToEnum, but not exposed as an extension of string, and differently named.
          If you were using it, please now use ParseToEnum.

Exceptions and Edge Cases

All the Generic methods are constrained as T: struct, IConvertible, which I believe to be as close to "is an Enum" as one can get in generic Type constraints. There is a further reflection-based check in the code, so calling any of them with T as a non-Enum will throw an InvalidOperationException.

  • Calling GetStringValue when no string value is defined
  • ...... will return enum Name
  • Calling ParseToEnum<T>() when the string is null
  • ...... will throw an ArgumentNullException
  • Calling ParseToEnum<T>() when the string doesn't match anything
  • ...... will throw an UnmatchedStringValueException()
  • Calling ParseToEnumList<T>() when any of the strings are null or don't match anything
  • ...... will throw an appropriate Exception depending on the first problem hit.
  • Calling GetStringValue when multiple values are defined but none are marked as preferred
  • ...... may return any of the string values.
  • Calling GetStringValue when multiple values are marked as preferred
  • ...... may return any of the preferred values.
  • Calling ParseToEnum<T>() when the string is defined for multiple Enums
  • ...... may return any of the Enums that it matches.

Note that in all of these 'may return any' cases, I suspect that it will always return the top-most value, but that will be dependant on .NET's implementation of various methods and is not in anyway guaranteed by this library! Frankly, any of these would be a mis-use of the library and could arguably throw instead.

If TryParseStringValueToEnum is called and fails, then it will populate the output variable to default(T), likely the first defined value of the Enum.

Rationale behind library

This library was initially constructed to allow an easy way to define the string value associated with each value of an Enumeration.
You can convert an Enum value to a string very easily, but only if the string you want is the name of that value - this library allows you to define any string and easily convert from that Enum to that string. The scenario in my case was wanting a piece of text to display to the user that wasn't forced to be CamelCase.

A natural extension of that was then to allow you to convert in the opposite direction - Given a string and an Enum Type return the enum that matches to that string. The scenario here, was reading a datafile into a program, and wanting to have one of the properties as an Enum.

Finally, it then seemed to be useful to allow you to define multiple possible strings that match to the Enum - so that it could handle the possibility that multiple different inputs should actually map to the same Enum. Once you're defining multiple strings for each enum, you then need to know which one to use when converting from enum to string, so add a property to mark one of those String Values as the 'Preferred' string value.

Version History

  • 3.0 - Convert the project to .Net Standard 2.0
    - Remove the Obsolete ParseStringValueToEnum method.

  • 2.0 - Make the library use the existing Enum name as its default string value
    - Exposed the Parse methods as extensions on String and List&lt;string&gt;
    - Added a clone of the basic Parse method renamed as ParseToEnum&lt;T&gt;
    - NOTE: The old parse method (ParseStringValueToEnum) is now deprecated and will be removed in vNext. ParseToEnum is identical and should be used instead.

  • 1.0 - Final cosmetic tweaks. (Project is now essentially complete and this is likely the last update in a while)

  • 0.11 - Update nuget files on build

  • 0.10 - Explicitly support recent major .NET versions.

  • 0.9 - Created a nuget package, so committing structure for that.

  • 0.8 - Upgrade to .NET 4.5.1

  • 0.7 - Make nuget manage the nUnit dependency.

  • 0.6 - Fix namespaces which previously related to my personal Utilities project :)

  • 0.5 - Rename Parse Methods to reflect the fact that they return Enums, not ints.

  • 0.4 - Improve Attribute constructor layout, and adjust access modifiers

  • 0.3 - Fix Null string handling.

  • 0.2 - Initial Readme.

  • 0.1 - Initial Upload.

Release Notes

Version 3.0
      - Convert the project to .Net Standard 2.0
      - Remove the Obsolete `ParseStringValueToEnum` method. Please use `ParseToEnum`

  • .NETFramework 3.5

    • No dependencies.
  • .NETFramework 4.0

    • No dependencies.
  • .NETFramework 4.5.1

    • No dependencies.
  • .NETFramework 4.6.1

    • No dependencies.
  • .NETStandard 2.0

    • No dependencies.

This package is not used by any popular GitHub repositories.

Version History

Version Downloads Last updated
4.0.0 896 5/28/2019
3.2.0 63 5/28/2019
3.1.0 63 5/28/2019
3.0.1 61 5/28/2019
3.0.0 21,258 12/9/2017
2.0.0 7,158 5/29/2015
1.0.0 556 7/13/2014
0.9.1 342 7/13/2014
0.9.0 387 4/15/2014