Question

Is there a way to set multiple enum values in a configuration section?

Like you do in .net object.Filter = Filter.Update | Filter.Create;

<wacther filter="update, created"/>

Is something like that supported?

Was it helpful?

Solution

Define a flag enum:

[Flags]
enum Filter
{
    None = 0,
    Update = 1,
    Create = 2
}

Assume you have a string of enum from your config file:

var enumString = "update, create";

So you can get the result:

var result = (Filter) Enum.Parse(typeof (Filter), enumString, true);

OTHER TIPS

It just works out of the box:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var section = (MySection)ConfigurationManager.GetSection("mySection");
            Console.WriteLine(section.Enum);
        }
    }

    public class MySection : ConfigurationSection
    {
        [ConfigurationProperty("enum")]
        public MyEnum Enum
        {
            get { return (MyEnum)this["enum"]; }
            set { this["enum"] = value; }
        }
    }

    [Flags]
    public enum MyEnum
    {
        None = 0,
        Foo = 1,
        Bar = 2,
        Baz = 4
    }
}


<configSections>
  <section name="mySection" type="ConsoleApplication1.MySection, ConsoleApplication1"/>
</configSections>

<mySection enum="Foo, Bar"/>

Prints: Foo, Bar

The easiest way is to use FlagsAttribute. But if you have already had the enum with the set of values, then you can use this code:

public static IEnumerable<T> GetEnumValues<T>(string enumValues)
{
    return string.IsNullOrEmpty(enumValues)
        ? Enumerable.Empty<T>()
        : enumValues.Split(',').Select(e => System.Enum.Parse(typeof(T), e.Trim(), true)).Cast<T>();
}

[ConfigurationProperty("filter")]
public string Filter => GetEnumValues<FilterEnum>((string) this["filter"]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top