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 NameValueSectionHandler
is fine for string
->string
pairs in simple situations, but if you need your configuration to be efficient (particularly if you're going to be using remove
repeatedly), use DictionarySectionHandler
.
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:
DictionarySectionHandler
stores its key/value pairs in a Hashtable
, whereas NameValueSectionHandler
uses a NameValueCollection
.DictionarySectionHandler
, the value
is not required and will default to an empty string if it is not provided, but NameValueSectionHandler
requires the value
.As far as the differences between Hashtable
and NameValueCollection
, NameValueCollection
can have duplicate keys, but Hashtable
cannot. Additionally, Hashtable
is pretty significantly more efficient in its implementation.
This article on the MSDN Blog has some good information about Hashtable
and NameValueCollection
.
To summarize their findings, Hashtable
is...
They wrap up the article with some helpful information on when to use NameValueCollection
:
So you may be wondering when you’d want to use NameValueCollection. NameValueCollection only accepts keys and values that are Strings, so this is a very specialized collection. It’s useful in a situation in which you either need to associate multiple values with a key, or to do hash-based lookups as well as lookup by index (and hopefully not perform too many removes).
However, if you need to store string key/value pairs and you don’t need to perform index-based lookups or associate multiple values with a key, you may prefer to use the generic Dictionary class. This has the same asymptotic behavior as Hashtable in all cases and furthermore avoids any costs due to boxing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With