Using custom names for the ConfigurationElementCollection entries
I have been using the .NET configuration library pretty extensively and one thing about using the ConfigurationElementCollection kind of just kept bothering me. All of my custom sections implementing ConfigurationElementCollection always used “add” as the default element name for its entries. I wanted it to be named something more meaningful than “add” which did not make sense all the time. For example, I wanted to be able to use “entry” as the element name instead of “add” like shown below.
Nothing the documentation for the .NET configuration stood out to me that will let me use a more meaningful name. Using a different custom name for the element entries didn’t turn out to be hard to. It was just a matter of looking in the right places to figure how to get it done. This can be accomplished by decorating the property of the custom ConfigurationElementCollection type in the ConfigurationSection with the ConfigurationCollectionAttribute and specifying the “AddItemName” which is an optional parameter like shown below.
public class TestSection: ConfigurationSection
{
public TestSection() { }
[ConfigurationProperty(“NameValues”, IsDefaultCollection = true)]
[ConfigurationCollection(typeof(NameValueElementCollection), AddItemName=“entry”)]
public NameValueElementCollection NameValues
{
get { return (NameValueElementCollection)base[“NameValues”]; }
}
}
[…] Using custom names for the ConfigurationElementCollection entries […]
After spending 20 hrs trying (almost banging my head) to get a collection of custom configuration, I came across your article and in next 5 mins I got it working.
You can not belive how thankful I am to you for posting this article!
Thanks for the post. It helped me also. 🙂
Great! Thanx for the tip, it helped.
Thanks, works like a charm
Definitely saved me some time! Thanks!
Many thanks, this was driving me insane
hi instead of namevaluecollection i want to use my custom class(X) collection which has 4 properties. How do i do that ?
It says Class X as “Unrecognized element”.