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).
I don’t believe there’s anything built into .NET which provides the functionality you’re looking for.
You could create a class based on
Dictionary<TKey, TValue>that provides an overload ofTryGetValuewith an additional argument for a default value, e.g.:You could probably get away with
strings instead of keeping in generic.There’s also DependencyObject from the Silverlight and WPF world if those are options.
Of course, the simplest way is something like this with a
NameValueCollection:keycan benullon the string indexer. But I understand it’s a pain to do that in multiple places.