In .NET, we can create custom configuration sections using the <configSections> element, like so:
<configuration>
<configSections>
<section name="dictionarySample"
type="System.Configuration.DictionarySectionHandler"/>
<section name="nameValueSample"
type="System.Configuration.NameValueSectionHandler" />
</configSections>
<dictionarySample>
<add key="key1"
value="value1"/>
</dictionarySample>
<nameValueSample>
<add key="key2"
value="value2" />
</nameValueSample>
</configuration>
Above, I am defining two sections. One of type DictionarySectionHandler, and another of type NameValueSectionHandler.
As far as I can tell, these two Handlers are used in exactly the same way and result in identical configuration sections.
So, is there a difference, or can I use them interchangeably?
TL;DR
NameValueSectionHandleris fine forstring->stringpairs in simple situations, but if you need your configuration to be efficient (particularly if you're going to be usingremoverepeatedly), useDictionarySectionHandler.I dug into the source of these two classes (NameValue, Dictionary), and found very little difference in implementation.
There are two things worth noting, though:
DictionarySectionHandlerstores its key/value pairs in aHashtable, whereasNameValueSectionHandleruses aNameValueCollection.DictionarySectionHandler, thevalueis not required and will default to an empty string if it is not provided, butNameValueSectionHandlerrequires thevalue.As far as the differences between
HashtableandNameValueCollection,NameValueCollectioncan have duplicate keys, butHashtablecannot. Additionally,Hashtableis pretty significantly more efficient in its implementation.This article on the MSDN Blog has some good information about
HashtableandNameValueCollection.To summarize their findings,
Hashtableis...They wrap up the article with some helpful information on when to use
NameValueCollection: