I\'d like to create a Dictionary object, with string Keys, holding values which are of a generic type. I imagine that it would look something like this:
Dict
I didn't find what I was looking for here but after reading I think it might be what is being asked for so an attempt to answer.
The problem is that when you use Dictionary it is a closed constructed type and all elements must be of the TValue type. I see this question in a number of places without a good answer.
Fact is that I want indexing but each element to have a different type and based on the value of TKey we already know the type. Not trying to get around the boxing but trying to simply get more elegant access something like DataSetExtensions Field. And don't want to use dynamic because the types are known and it is just not wanted.
A solution can be to create a non generic type that does not expose T at the class level and therefore cause the TValue part of the dictionary to be closed constructed. Then sprinkle in a fluent method to help initialization.
public class GenericObject
{
private object value;
public T GetValue()
{
return (T)value;
}
public void SetValue(T value)
{
this.value = value;
}
public GenericObject WithValue(T value)
{
this.value = value;
return this;
}
}
class Program
{
static void Main(string[] args)
{
Dictionary dict = new Dictionary();
dict["mystring"] = new GenericObject().WithValue("Hello World");
dict["myint"] = new GenericObject().WithValue(1);
int i = dict["myint"].GetValue();
string s = dict["mystring"].GetValue();
}
}