C# - Dictionary with generic array as value

Posted by alhazen on Stack Overflow See other posts from Stack Overflow or by alhazen
Published on 2011-01-09T22:33:55Z Indexed on 2011/01/09 22:53 UTC
Read the original article Hit count: 246

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET