EnumStringValues 3.0.0

Details
Advisory: https://github.com/advisories/GHSA-vq23-hwg7-hxrh Severity: low
There is a newer version of this package available.
See the version list below for details.
dotnet add package EnumStringValues --version 3.0.0
NuGet\Install-Package EnumStringValues -Version 3.0.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<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
#r "nuget: EnumStringValues, 3.0.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install EnumStringValues as a Cake Addin
#addin nuget:?package=EnumStringValues&version=3.0.0

// Install EnumStringValues as a Cake Tool
#tool nuget:?package=EnumStringValues&version=3.0.0

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<string> - Added a clone of the basic Parse method renamed as ParseToEnum<T> - 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.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net35 is compatible.  net40 is compatible.  net403 was computed.  net45 was computed.  net451 is compatible.  net452 was computed.  net46 was computed.  net461 is compatible.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .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.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on EnumStringValues:

Package Downloads
SanNuo.ERP.WebApis.Domain.Common

Package Description

IntisTelecom

UK Intis Telecom LTD Company number 11767499 100 New Bond Street First Floor, London, United Kingdom, W1S 1SP VAT: GB323461428

HandheldGroup.Scanner

Scanner SDK

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
4.0.2 196,204 1/5/2020
4.0.1 2,086 1/2/2020
4.0.0 56,120 5/28/2019
3.2.0 1,327 5/28/2019
3.1.0 1,294 5/28/2019
3.0.1 1,271 5/28/2019
3.0.0 56,553 12/9/2017
2.0.0 12,565 5/29/2015
1.0.0 2,247 7/13/2014
0.9.1 1,792 7/13/2014
0.9.0 2,062 4/15/2014

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