Does ConfigurationElementCollection preserve order

512 views Asked by At

I need to store a list of objects to a configuration section in their prioritized order.

If I go with the standard implementation of extending ConfigurationElementCollection and ConfigurationElement (similar to what is described here). Will the order of the collection be preserved when the config file is read from and written to?

Edit: Some sample code.

Given this:

class Program
{
    static void Main(string[] args)
    {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var section = config.GetSection("TestSection") as TestSection;
        foreach (MyElement item in section.HopefullyOrderedItems)
        {
            Console.WriteLine(item.ElementValue);
        }
        Console.ReadLine();
    }
}

public class TestSection : ConfigurationSection
{
    [ConfigurationProperty("ListOfThings")]
    [ConfigurationCollection(typeof(MyCollection))]
    public MyCollection HopefullyOrderedItems
    {
        get { return (MyCollection) this["ListOfThings"]; }
        set { this["ListOfThings"] = value; }
    }

}

public class MyCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new MyElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((MyElement) element).ElementValue;
    }

    new public MyElement this[string name]
    {
        get { return (MyElement) BaseGet(name); }
    }
}

public class MyElement : ConfigurationElement
{
    [ConfigurationProperty("ElementValue")]
    public string ElementValue
    {
        get { return (string) this["ElementValue"]; }
        set { this["ElementValue"] = value; }
    }
}

With this app.config:

<configuration>
    <configSections>
        <section name="TestSection" type="testestes.TestSection, testestes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="true" />
    </configSections>
    <TestSection>
        <ListOfThings>
            <add ElementValue="qwerty" />
            <add ElementValue="asdfgh" />
        </ListOfThings>
    </TestSection>
</configuration>

When I access the list of things in code, is it guaranteed to be in the same order as specified in the config?

0

There are 0 answers