I have a very abstract problem ahead of me.
I have a class that has a public property of type Dictionary<string, object>
the job of this dictionary is to hold custom user settings and their values.
There are no constraints on the settings but generally they are similar to:
"Brightness", 100
"Connection, "TCP"
So when I instantiate this class its dictionary property will be filled with the names of the settings and their corresponding values.
The problem is retrieving a value.
Since the values can be ints, strings, etc. they are stored as an object
in the dictionary but I need to retrieve them as a concrete type.
While I can use dict["Brightness"].GetType()
to find out what the type or use pattern matching I am having trouble figuring out what method return type to use.
I thought that, maybe, I can use a separate "result" property for each type and based on the value's type assign the corresponding value to the correct property, so like if the "Brightness" is 100, then have a method that tests the type of the value of "Brightness" and upon seeing it is int do something like
int resultInt;
resultInt = (int)dict["Brightness"];
But something tells me this is ugly and there is a better way.
Furthermore this is not threadsafe.
Additional information on the program's purpose:
The program's idea is to be able to, basically, store a bunch of settings and their values for different systems. They are always in a key-value relationship, keys are unique and values can be anything. They can be strings, ints, floats, decimal, etc. The purpose of the program is user customisation, in a way.
What I mean by this is - the user enters what settings he wants stored. What he enters becomes the full list of possible settings that the program will work with. He then enters values for these settings for each system or "device" that he has. So, for example, he says "I have a computer and a smartphone". Enters the settings "Brightness" and "CPU" into the program. Now the program knows all systems he configures will have these two settings with possibly different values associated with them.
So then the user can say "I want my smartphone screen brightness to be 80%." so he enters the int "80" as the value of "Brightness" for the entry that will correspond to his smartphone. Similarly he can enter a different value for his home computer.
Bottom line I never know what types will need to be stored.
If you don't know at compile time what type is in your dictionary, you can use the dynamic
tag (reworking the example of Patrick):
public dynamic GetValueOrDefault(string key)
{
if (this.dictionary.TryGetValue(key, out object o))
{
return o;
}
return null;
}
Use case:
int val;
val = dict.GetValueOrDefault("Brightness");
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments