Created
June 17, 2016 06:05
-
-
Save justinyoo/21df632098d698c9be7c525464998908 to your computer and use it in GitHub Desktop.
Configuration Value Converter for enum and List<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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