ReadOnlyNameValueCollection (reading from ConfigurationManager.GetSection)

fearofawhackplanet picture fearofawhackplanet · May 16, 2011 · Viewed 7.1k times · Source

Ok, so.....

<section name="test" type="System.Configuration.NameValueFileSectionHandler" />
<test>
   <add key="foo" value="bar" />
</test>

var test = ConfigurationManager.GetSection("test");

So far so good. The debugger shows test contains one key, foo.

But GetSection returns object, so we need a cast:

var type = test.GetType();
// FullName: System.Configuration.ReadOnlyNameValueCollection
// Assembly: System

Ok, this should be simple enough. So....

using System;

var test = ConfigurationManager
               .GetSection("test") as ReadOnlyNameValueCollection;

error!

The type or namespace ReadOnlyNameValueCollection does not exist in the namespace System.Configuration. Are you missing an assembly reference?

err... wtf?

A cast to System.Collections.Specialized.NameValueCollection gets the code working, but I don't really understand why the error.

And a search for ReadOnlyNameValueCollection on MSDN shows there is no documentation on this class at all. It doesn't seem to exist. Yet I have an instance of that type in my code.

Answer

Tim picture Tim · May 16, 2011

System.Configuration.ReadOnlyNameValueCollection is an internal class to the System.dll assembly. So you can't refer to it from your code. It derives from System.Collections.Specialized.NameValueCollection, though, so that's why you're able to do that with the cast.