Can I Create a Dictionary of Generic Types?

Would something like this work?

public class GenericDictionary
{
    private Dictionary<string, object> _dict = new Dictionary<string, object>();

    public void Add<T>(string key, T value) where T : class
    {
        _dict.Add(key, value);
    }

    public T GetValue<T>(string key) where T : class
    {
        return _dict[key] as T;
    }
}

Basically it wraps all the casting behind the scenes for you.


EDIT: Now I've reread the question...

You can't do this, but a custom collection would handle it to some extent. You'd basically have a generic Add method:

public void Add<T>(string key, List<T> list)

(The collection itself wouldn't be generic - unless you wanted to make the key type generic.)

You couldn't extract values from it in a strongly typed manner though, because the compiler won't know which type you've used for a particular key. If you make the key the type itself, you end with a slightly better situation, but one which still isn't supported by the existing collections. That's the situation my original answer was responding to.

EDIT: Original answer, when I hadn't quite read the question correctly, but which may be informative anyway...

No, you can't make one type argument depend on another, I'm afraid. It's just one of the things one might want to express in a generic type system but which .NET's constraints don't allow for. There are always going to be such problems, and the .NET designers chose to keep generics relatively simple.

However, you can write a collection to enforce it fairly easily. I have an example in a blog post which only keeps a single value, but it would be easy to extend that to use a list.


How about Dictionary<string, dynamic>? (assuming you're on C# 4)

Dictionary<string, dynamic> Dict = new Dictionary<string, dynamic>();

Source: https://stackoverflow.com/a/5038029/3270733

Tags:

C#

Generics