I have the following code, which stores a list of actions to perform based on the type of value passed as an argument...
Action<int> intAction = x => Console.WriteLine($"You sent an int: {x}");
Action<bool> boolAction = x => Console.WriteLine($"You sent a bool: {x}");
var funcsByInputType = new Dictionary<Type, Action<object>>();
funcsByInputType[typeof(int)] = (object x) => intAction((int)x);
funcsByInputType[typeof(bool)] = (object x) => boolAction((bool)x);
PerformAction(true);
PerformAction(42);
void PerformAction<TValue>(TValue value)
{
if (funcsByInputType!.TryGetValue(typeof(TValue), out Action<object>? action))
{
action(value!);
}
}
This works as expected.
What I now want to do is create the dictionary from a single method that I only call once, so I can rewrite my code like this instead.
Action<int> intAction = x => Console.WriteLine($"You sent an int: {x}");
Action<bool> boolAction = x => Console.WriteLine($"You sent a bool: {x}");
funcsByInputType = MakeFuncsByInputType(intAction, boolAction);
PerformAction(true);
PerformAction(42);
void PerformAction<TValue>(TValue value)
{
if (funcsByInputType!.TryGetValue(typeof(TValue), out Action<object>? action))
{
action(value!);
}
}
How could I write the MakeFuncsByInputType method?
Note that I don't want to make multiple calls to the method, and I don't want to have my parameters defined as params object[]