Simple trick thatsaves me some time and coding when writing custom configuration objects is to define generic collection for them. Let’s say Icreated several custom configuration elements derived from my CustomConfigElementBasewhich in turninheritsfrom System.Configuration.ConfigurationElement. Instead of defining collectionsfor each type (derived from ConfigurationElementCollection) I can simply define class:

public class GenericConfigElementCollection<T> : ConfigurationElementCollection

where T : CustomConfigElementBase, new()

{

public T this[int index]

{

get

{

return base.BaseGet(index) as T;

}

set

{

if (base.BaseGet(index) != null)

base.BaseRemoveAt(index);

base.BaseAdd(index, value);

}

}

protected override ConfigurationElement CreateNewElement()

{

returnnew T();

}

protected overrideobject GetElementKey(ConfigurationElement element)

{

return ((T)element).ElementKey;

}

}

Note, that base custom configuration element has property ElementKey to satisfy GetElementKey method implementation. If your custom elements have different keys, you canoverride this property.

Now, when we defineconfiguration section we just return generic collection of appropriate type:

public class MyCustomConfigSection : ConfigurationSection

{

[ConfigurationProperty(“myCustomSettings”, IsRequired = true)]

public GenericConfigElementCollection<MyCustomConfigElement> MyCustomSettings

{

get

{

return this[“myCustomSettings”]

as GenericConfigElementCollection<MyCustomConfigElement>;

}

}

}

And then just use it in anapplication code:

GenericConfigElementCollection<MyCustomConfigElement> configCollection = configSection.MyCustomSettings;

MyCustomConfigSection configSection = (MyCustomConfigSection)ConfigurationManager.GetSection(“mySection”);