Skip to content

Instantly share code, notes, and snippets.

@justinyoo
Created June 17, 2016 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinyoo/21df632098d698c9be7c525464998908 to your computer and use it in GitHub Desktop.
Save justinyoo/21df632098d698c9be7c525464998908 to your computer and use it in GitHub Desktop.
Configuration Value Converter for enum and List<T>
public class PipeDelimitedFlaggedEnumConverter<TEnum> : ConfigurationConverterBase where TEnum : struct
{
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var segments = ((string)value).Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
var converted = 0;
foreach (var segment in segments)
{
TEnum result;
if (!Enum.TryParse((string)segment, true, out result))
{
throw new InvalidOperationException($"Invalid enum value - {segment}");
}
converted += Convert.ToInt32(result);
}
return (TEnum)Enum.ToObject(typeof(TEnum), converted);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment