Reputation: 1915
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.
Upvotes: 0
Views: 5615
Reputation: 283684
You don't cast to T[]
, you use System.Array
, the base class for all arrays.
var dictionary = new Dictionary<string, Array>();
foreach( var item in dictionary )
item.Value.SetValue(null, 0);
Other operations you can do without having to cast to a specific array type are Array.Clear
and Buffer.BlockCopy
.
Upvotes: 2
Reputation: 28718
You should use a generic class. The advantage of using a generic class if that the object retrieved from the dictionary is type-safe and does not require casting - it will already be of the required type.
You say that 'the operations of my class are exactly the same for all generic types' - if that means what I think it means then it is merely reinforcing the usefulness of a generic class in your case.
Upvotes: 1
Reputation: 52185
Since the operations of my class are exactly the same for all generic types
What you can do, is define all the methods which are the same in an interface and make your generic classes implement that interface. Once you do that, all that you need to do is to create a dictionary which takes Strings as keys and arrays of type InterfaceName
. This should allow you to have generic values (instead of the object
) and you will not need to type cast either.
Upvotes: 2