Thomas
Thomas

Reputation: 1565

How to create a Generic Dictionary?

I have a Class where i have a Dictionary holding a specific Key. But the Value should be generic.

Something like:

private Dictionary<String,TValue> _Dictionary;

But TValue is not found (obvesly) but what else should i put in? I found a solution for IList but i just want to add one Generic Object.

Upvotes: 2

Views: 5996

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564901

If you're using this within a generic type, Tejs answer is appropriate.

However, if you're just trying to make a dictionary with a fixed type of key, but which can store any value, one option is to just use System.Object for your value:

 private Dictionary<string, object> _dictionary;

This will allow you to assign any object into the value. However, this is potentially dangerous, as you lose type safety and need to make sure to unbox and convert the object correctly.

Upvotes: 2

Tejs
Tejs

Reputation: 41266

So you want a generic dictionary? Use the pre defined class.

public Dictionary<int, string> _dictionary = new Dictionary<int, string>();

That gives you a dictionary with an integer key, and a string value. If you need a Dictionary with only one of those being variable, you can inherit Dictionary to make your own type.

public class KeyTypeConstantDictionary<T> : Dictionary<int, T>
{
}

Then using it is like so:

KeyTypeConstantDictionary<string> x = new KeyTypeConstantDictonary<string>();
// Equivalent to Dictionary<int, string>()
KeyTypeConstantDictionary<SomeObject> x = new KeyTypeConstantDictonary<SomeObject>();
// Equivalent to Dictionary<int, SomeObject>()

Hopefully I understood your question correctly.

Upvotes: 2

Related Questions