<PackageReference Include="System.Configuration.ConfigurationManager" Version="5.0.0-preview.3.20214.6" />

GenericEnumConverter

Converts between a string and an enumeration type.
using System.ComponentModel; using System.Globalization; using System.Text; namespace System.Configuration { public sealed class GenericEnumConverter : ConfigurationConverterBase { private readonly Type _enumType; public GenericEnumConverter(Type typeEnum) { if (typeEnum == (Type)null) throw new ArgumentNullException("typeEnum"); _enumType = typeEnum; } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { return value.ToString(); } public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { string text = data as string; if (text != null && text.Length > 0 && !char.IsDigit(text[0]) && text[0] != '-' && text[0] != '+' && !char.IsWhiteSpace(text[0]) && !char.IsWhiteSpace(text[text.Length - 1])) try { return Enum.Parse(_enumType, text); } catch { } throw CreateExceptionForInvalidValue(); } private ArgumentException CreateExceptionForInvalidValue() { StringBuilder stringBuilder = new StringBuilder(); string[] names = Enum.GetNames(_enumType); foreach (string value in names) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(value); } return new ArgumentException(System.SR.Format(System.SR.Invalid_enum_value, stringBuilder)); } } }