Skip to content

Instantly share code, notes, and snippets.

@justinyoo
Created June 17, 2016 06:03
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/b996c319e8f7bfde70d3626a6b68bcdf to your computer and use it in GitHub Desktop.
Save justinyoo/b996c319e8f7bfde70d3626a6b68bcdf to your computer and use it in GitHub Desktop.
Configuration Value Converter for enum and List<T>
public class CommaDelimitedListConverter<T> : ConfigurationConverterBase
{
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 result = segments.Select(p => (T)ChangeType(typeof(T), p.Trim())).ToList();
return result;
}
private static object ChangeType(Type type, string value)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
object result;
if (type.IsEnum)
{
result = Enum.Parse(type, value, true);
return result;
}
result = Convert.ChangeType(value, type);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment