Search code examples
c#.netconfigurationsection

Why does ConfigurationSection need to look things up with a string?


The ConfigurationSection examples I have found online (for example) all have code that looks like this:

public class ConnectionSection  : ConfigurationSection
{
    [ConfigurationProperty("Servers")]
    public ServerAppearanceCollection ServerElement
    {
        get { return ((ServerAppearanceCollection)(base["Servers"])); }
        set { base["Servers"] = value; }
    }
}

Why is it accessing the value "Servers" from the base using the square brackets? Is the setter used when creating this object from the xml, or is the setter used to overwrite the value in the xml file? If so, why is the attribute set on this property?


Solution

  • Why is it accessing the value "Servers" from the base using the square brackets?

    Because the base class, ConfigurationSection, doesn't know what properties its inheritors are going to implement.

    So it exposes a string indexer: this[string] which lets you access the values read from the configuration.

    This was a design decision. The .NET team could also have opted to use reflection to get and set the inheritor's properties, but decided not to. (Well, of course there's lots of reflection going in in configuration sections, but not up till the point that public ServerAppearanceCollection ServerElement { get; set; } would work).