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 of TryGetValue
with an additional argument for a default value, e.g.:
public class MyAppSettings<TKey, TValue> : Dictionary<TKey, TValue>
{
public void TryGetValue(TKey key, out TValue value, TValue defaultValue)
{
if (!this.TryGetValue(key, out value))
{
value = defaultValue;
}
}
}
You could probably get away with string
s 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
:
string value = string.IsNullOrEmpty(appSettings[key])
? defaultValue
: appSettings[key];
key
can be null
on the string indexer. But I understand it's a pain to do that in multiple places.