I need to create a Dictionary object as a member field
key = string
value = an instance of Action<T> where T could be different per entry, e.g. long, int, string (a ValueType or a RefType)
However can’t get the compiler to agree with me here.. To create a member field it seems to need a fixed T specification. I’ve passed my limit of struggle time before awareness that ‘It shouldn’t be this difficult’
Might be a generics noob mistake. Please enlighten..
The usage would be something like this
m_Map.Add("Key1",
new delegate(long l) {Console.Writeline("Woohoo !{0}", l.ToString();));
You can’t, basically. How would the compiler know what type you were interested in for any particular entry?
You can’t even explain a relationship of
Dictionary<Type, Action<T>>where each dictionary entry has a key which is a type and an action which uses that type. Generics just doesn’t support that relationship.If you will know the kind when you try to use it, you can just make it a
Dictionary<string, Delegate>and cast the value when you fetch it. Alternatively, you could useAction<object>and live with the boxing and cast you’ll end up with.Note that to use anonymous methods or lambda expressions with just
Delegate, you’ll need to cast – or write a handy conversion method:That way you can write:
or in the dictionary context:
You’ll still need to cast to the right type when you fetch the value out of the dictionary again though…
A different tack…
Instead of exposing a dictionary directly, you could encapsulate the dictionary in your own type, and have a generic
Addmethod:So it would still be a
Dictionary<string, Delegate>behind the scenes, but your type would make sure that it only contained values which were delegates taking a single argument.