GeekCodingMaster GeekCodingMaster - 1 year ago 117
C# Question

Pass arguments to an action in dictionary at initialization C#

I have a

which has
as a key and an
as value,h however I want to give the
parameters at the initialization of the dictionary like this :

someDictionary = new Dictionary<KeyCode, Action<int>>()
{KeyCode.Alpha1, GoToCameraPosition(0) },

How can I do that ?

Answer Source

This is called currying. Note that the second type parameter to Dictionary has changed from your original: The action you create has no parameters, because the parameter for the action it calls is built into the anonymous lambda stored in the dictionary.

someDictionary = new Dictionary<KeyCode, Action>()
    {KeyCode.Alpha1, () => GoToCameraPosition(0) },

Call like so:

KeyCode key = KeyCode.Alpha1;
Action act = null;

if (someDictionary.TryGetValue(key, out act))
    //  act is a method that calls GoToCameraPosition(0)


foreach (var kvp in someDictionary)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download