Hasan A Yousef Hasan A Yousef - 29 days ago 11
C# Question

C# Invoke Action by reference

I'm new to C#, and it looks I need to use

Dictionary<string, Action>

So I wrote the below code:

using System;
using System.Collections.Generic;

public class Program
{


public static void Main()
{

var functions = new Dictionary<string, Action<string[]>>();
functions.Add("Foo", CountParameters);
functions.Add("Bar", SomeOtherMethodName);

Console.WriteLine("Hello World");

Action<string[]> action;
if (functions.TryGetValue("Foo", out action))
{
action();
// What shall I write here to invoke the action!?
}
else
{
// No function with that name
}

}


public static void CountParameters(string[] args)
{
Console.WriteLine("Fn 1");
}

public static void SomeOtherMethodName(string[] args)
{
Console.WriteLine("Fn 2");
}
}


My Question is of 2 parts:
1. How shall I invoke the
Action
if the condition is true.
2. I understood the
Action
is a
Func
with
void
return, but it looks an input
args
is a must, in my case, i do not have an
input args
nor an
output
so is
Action
what I need, or could be something else?

Answer

If all your methods don't don't have return values, an Action<string[]> is fine. If they even don't require parameters, you could simply use the non-generic Action-delegate and leave out the string[]-parameter.

var functions = new Dictionary<string, Action>();
functions.Add("Foo", CountParameters);
...

Regarding the invocation: The way you've done it in your code snippet is fine if you leave out the (unnecessary) string[]-parameter. Just invoke the Action-delegate taken from the dictionary like you already did without any parameters: action();

Instead of attaching the brackets () you could alternatively call action.Invoke();.

Comments