AppSettings fallback/default value?

lance picture lance · Sep 21, 2010 · Viewed 10.2k times · Source

ASP.NET

For each appSetting I use, I want to specify a value that will be returned if the specified key isn't found in the appSettings. I was about to create a class to manage this, but I'm thinking this functionality is probably already in the .NET Framework somewhere?

Is there a NameValueCollection/Hash/etc-type class in .NET that will let me specify a key and a fallback/default value -- and return either the key's value, or the specified value?

If there is, I could put the appSettings into an object of that type before calling into it (from various places).

Answer

Carter Medlin picture Carter Medlin · Aug 30, 2017

This is what I do.

WebConfigurationManager.AppSettings["MyValue"] ?? "SomeDefault")

For Boolean and other non-string types...

bool.Parse(WebConfigurationManager.AppSettings["MyBoolean"] ?? "false")