AppSettings Return Values using ConfigurationManager
Posted on: Monday, December 21, 2015ConfigurationManager
uses the following rules to determine what to return when indexing into the AppSettings
collection:
- If there is a value present, return it as a string.
- If there is no value present (empty string), return an empty string.
- If there is no value attribute defined, return an empty string.
- If there is no matching key defined, return
null
.
Example
Given these settings:
<appSettings>
<add key="Key1" value="abc123" />
<add key="Key2" value="" />
<add key="Key3" />
</appSettings>
And the following code:
Console.WriteLine($"[{ConfigurationManager.AppSettings["Key1"] ?? "NULL"}]");
Console.WriteLine($"[{ConfigurationManager.AppSettings["Key2"] ?? "NULL"}]");
Console.WriteLine($"[{ConfigurationManager.AppSettings["Key3"] ?? "NULL"}]");
Console.WriteLine($"[{ConfigurationManager.AppSettings["Key4"] ?? "NULL"}]");
The following output is produced:
[abc123]
[]
[]
[NULL]