Configuration element containing a collection of child elements

app-config, c#, configuration, web-config

Solution

Neither, you would introduce a new ConfigurationCollectionElement instead e.g.

Section

class MyMainSection : ConfigurationSection
{
    [ConfigurationProperty("", IsRequired=true, IsDefaultCollection=true)]
    public AddElementCollection Instances 
    {
        get { return (AddElementCollection) this[""]; }
        set { this[""] = value; }
    }
}

Collection

public class AddElementCollection : ConfigurationElementCollection 
{
    protected override ConfigurationElement CreateNewElement() 
    {
        return new AddElement();
    }

    protected override object GetElementKey(ConfigurationElement element) {
        return ((AddElement) element).Name;
    }
}

Element

private class AddElement: ConfigurationElement
{
    [ConfigurationProperty("name", IsKey=true, IsRequired=true)]
    public string Name 
    {
        get { return (string) base["name"]; }
        set { base["name"] = value; 
    }
    ...
}

Problem

I want to have a custom section in my web.config like so: ``` <MyMainSection attributeForMainSection = "value foo"> <add name = "foo" type = "The.System.Type.Of.Foo, Assembly, Qualified Name Type Name" /> <add name = "bar" type = "The.System.Type.Of.Bar, Assembly, Qualified Name Type Name" /> </MyMainSection> ``` I have defined the following code: ``` using System.Configuration; class MyMainSection : ConfigurationSection { /*I've provided custom implemenation. Not including it here for the sake of brevity. */ [ConfigurationProperty("attributeForMainSection")] public string AttributeForMyMainSection { get; set; } [ConfigurationProperty("add")] public AddElement TheAddElement { get; set; } private class AddElement: ConfigurationElement { /* Implementation done */ } } ``` Should this property `TheAddElement` be `IEnumerable<AddElement>` or just `AddElement` if I want to allow multiple add elements?

Original source