GeekCodingMaster GeekCodingMaster - 4 months ago 21
C# Question

Pass arguments to an action in dictionary at initialization C#

I have a

Dictionary
which has
KeyCode
as a key and an
Action<int>
as value,h however I want to give the
Action
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

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)
    act();
}

Or

foreach (var kvp in someDictionary)
{
    kvp.Value();
}