Patrick
Patrick

Reputation: 5592

c# store different settings in one object

I have an object that represents the current event that is taking place. This event contains a lot of settings. What is the best practice for storing all setting variables inside the event object?

The settings are stored in a database (right now in different columns based on the base class: ValueString, ValueInt, ValueBool, ValueDateTime, ValueFloat, ValueDecimal). A unique key represents the setting in the database.

As soon as i have loaded the events object i will store it in the local cache for quick access.

Should i cast everything to object? (Feels like un-needed casts to get/set settings)

class Event
{
    // string = settings key
    Dictionary<string, object> _settings;

    public void AddSetting(string key, object value)
    public object GetSetting(string key)
}

or should i have it in different dictionaries?

class Event
{
    // string = settings key
    Dictionary<string, string> _settingStrings;
    Dictionary<string, int> _settingInts;
    ...

    public void AddSetting(string key, string value)
    public void AddSetting(string key, int value)
    ...

    public string GetStringSetting(string key)
    public int GetIntSetting(string key)    
    ...
}

Any ideas?

Upvotes: 2

Views: 166

Answers (2)

Fabian Bigler
Fabian Bigler

Reputation: 10895

I really do like dasblinkenlight's answer.

Except instead of wasting one column for each datatype, I would rather have only one column (likely a VARCHAR) on your datatable.

Advantages of this:

  • Faster reading (Only one indexed column)
  • Saving up storage (Only one varchar per row)

And then you can either use generics as mentioned, or cast the string object in your implementation to your wished type.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

You can store everything as an Object, but rather than performing a straight cast, use generics to build an easy to use API:

private IDictionary<string,object> _settings = new Dictionary<string,object>();

public void AddSetting<T>(string key, T value) {
    _settings[key] = value;
}
public T GetSetting<T>(string key, T notFound = default(T)) {
    object res;
    if (!_settings.TryGetValue(key, out res) || !(res is T)) {
        return notFound;
    }
    return (T)res;
}

The cast remains there, but the API hides it from the user: now the user can safely write

string searchPath = settingContainer.GetSetting<string>("searchPath");
int retryCount = settingContainer.GetSetting<int>("retryCount", -1);

Upvotes: 5

Related Questions