views:

38

answers:

3

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).

A: 

I think the machine.config under C:\%WIN%\Microsoft.NET will do this. Add keys to that file as your default values.

http://msdn.microsoft.com/en-us/library/ms228154.aspx

Dave Swersky
Machine.config would give me a fallback value, but I wouldn't be able to specify it in code? Is that right? I'm looking for something that lets me specify, in the code, the value that should be returned if the appSettings doesn't have the key I specify. I mention appSettings, but this question is as much about any NameValueCollection/Hash as it is about appSettings (or *.config) specifically.
lance
A: 

You can make a custom configuration section and provide default values using the DefaultValue attribute. Instructions for that are available here.

Richard Hein
Another good answer that shows how poorly I've asked my question. I may need to specify different fallback/default values depending on the caller (and/or values which are determined only at runtime). I shouldn't have mentioned appSettings, as I really need, simply, a NameValueCollection-type object that lets me specify the value to return if the key isn't found.
lance
A: 

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 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:

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.

Mike McCaughan