Search code examples
c#dictionarycastingobject-type

C#: Using a generic dictionary <key, object> to hold settings of mixed type and return correct value and typecast


I am trying to implement a class to hold user settings in an elegant and easy to maintain manner. There is an extensive list of possible settings with several types of settings(int, double, string etc...). I was trying to use a dictionary but since my types are mixed I used the generic object type as key return value. I also have another dictionary holding the type associated with each setting for reference. My problem is that I wish to create a lookup function that not only returns the specific setting value but also casts it correctly to the appropriate type. Since my dictionary holds object type, my function also has to return object type. But I am trying to avoid having to type out Get and Set for each possible setting. Is there an elegant solution (even that may involve typing a little more code) that any one can share?


Solution

  • For a quick and lightweight solution, you should consider using a dynamic value type:

    var settings = new Dictionary<string, dynamic>();
    settings["FavoriteWidget"] = "Gizmo";
    settings["Weight"] = 0.5
    
    string favoriteWidget = settings["FavoriteWidget"];
    double weight = settings["Weight"];
    

    You can read more about dynamic here: Using Type dynamic (C# Programming Guide)