tags:

views:

107

answers:

4

One of the previous developers where I work habitually, consistently used:

 ConfigurationSettings.AppSettings["Foo"].ToString()

It twigs me a bit since AppSettings collection items are already strings, but I got to wondering: way back in the ancient days of .net 1.0 and 1.1, did the collection store its items as type Object necessitating the ToString() call?

A: 

I don't think so.

Mehrdad Afshari
+5  A: 

No, AppSettings has always been a NameValueCollection with a string key and a string value.

Source: MSDN

John Rasch
A: 

no the appsettings in 1.1 is NameValueCollection of strings, i was reviewing a solution in vs2003 and i also find the ToString() while getting the appsettings; maybe it is a developer habit

Oscar Cabrero
+3  A: 

As John already mentioned, ConfigurationSettings.AppSettings is a NameValueCollection which returns it's items as Strings.

Personally, I hate to see this kind of code... people attaching a ToString() call to just about every property, regardless of whether it returns a string in the first place. Unfortunately, I get to see it all too often. My guess is that it makes people feel comforted... somehow, as if they're following recommended guidelines for writing beautiful code. :P

What they don't seem to realize is that calling ToString() on a Null object will throw an exception. For instance, in your example, if the "Foo" key did not exist in the AppSettings section of Configuration, a NullReferenceException would be thrown by the code.

Cerebrus
+1 for pointing that out, maybe he even setup the code to catch that exception to tell the user that the key doesn't exist
John Rasch