C# - Dictionary with generic array as value
- by alhazen
In my class, I want to use a dictionary with the following declaration:
Dictionary<string, T[]>
Since the operations of my class are exactly the same for all generic types, I do not wish to define my class as generic (which means I would have to create a separate instance of my class for each generic type I insert into the dictionary ?).
One alternative I'm attempting is to use Dictionary<string, object> instead:
public void Add<T>(string str, T value)
{
// Assuming key already exists
var array = (T[]) dictionary[str];
array[0] = value;
}
However, when iterating over the dictionary, how do I cast the object value back to an array ?
foreach(string strKey in dictionary.Keys)
{
var array = (T[]) dictionary[strKey]; // How to cast here ?
//...
array[0] = default(T);
}
Thanks.