Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will ConfigurationManager.AppSettings["blah"] throw an exception if "blah" doesn't exist?

No, it returns null.


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.


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.


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)


Other answers reference the documentation for the Item property. It might not be immediately obvious why they are relevant looking at the following code snippet.

ConfigurationManager.AppSettings["blah"]

The square bracket syntax is used in C# to access indexers. These are special properties that allow a class to be indexed in the same way that an array can be. Looking at the definition of the NameValueCollection.Item property, you will notice that it does not use the normal property syntax. The this keyword and the indexer parameters are used to define this property as an indexer.

public string this[
    string name
] { get; set; }

In the documentation, indexers are implicitly named Item and parameters are surrounded by square brackets.

Indexers as shown in the MSDN documentation.

It is not clear to me why there were answers that referenced the Get method - maybe one calls the other?

At any rate, to answer the question...

No. An exception will not be thrown if you access a non-existent key - a null will be returned.

Here is the relevant section from the NameValueCollection.Item property documentation.

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.


As Tim said, it will just return null.

However, if you want it to throw an exception when not found one could do this:

var myImportantSetting= ConfigurationManager.AppSettings["important_setting"] ?? throw new SettingsPropertyNotFoundException("AppSetting missing.");