views:

75

answers:

5

Will ConfigurationManager.AppSettings["blah"] throw an exception if "blah" doesn't exist in the web/app.config?

Sincere apologies for the super lazy question.

A: 

Yes http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx

Edit: this is clearly wrong. Left for the helpful comments below.

Ben Aston
@Ben the answer to your question is No like @Tim mentioned. The page pointed to just said that if appsettings are not able to be loaded then an exception is thrown. But if a value is just not present in the appsettings then you will not get an exception. It really wouldn't make sense to throw an error just because a value doesn't exist in a dictionary. But if the dictionary didn't exist then that would be a reason to throw an error. (The term dictionary was just used to refer to an arbitrary collection.)
spinon
That link says that an exception is thrown if the `NameValueCollection` could not be found - i.e. the system could not find *any* settings. Name Value Collections do not thrown an exception when you try to retrieve a single value that does not exist..
Dexter
+3  A: 

No, it returns null.

Tim Robinson
+1  A: 

From the MSDN documentation for NameValueCollection.Item Property (String):

Caution

This property returns null in the following cases: 1) if the specified key is not found; and 2) if the specified key is found and its associated value is null. This property does not distinguish between the two cases.

Martin Liversage
+1  A: 

No, it returns null.

ConfigurationManager.AppSettings is a NameValueCollection - from the MSDN documentation:

The Get method does not distinguish between null which is returned because the specified key is not found and null which is returned because the value associated with the key is null.

(my emphasis)

Andrew
+1  A: 

No, it returns null.

AppSettings is a NameValueCollection - as per the caution on the NameValueCollection.Get page:

This method returns a null reference (Nothing in Visual Basic) in the following cases: 1) if the specified key is not found; and 2) if the specified key is found and its associated value is a null reference (Nothing in Visual Basic). This method does not distinguish between the two cases.

Dexter