Hasan A Yousef Hasan A Yousef - 4 months ago 40
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))
// What shall I write here to invoke the action!?
// 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
if the condition is true.
2. I understood the
is a
return, but it looks an input
is a must, in my case, i do not have an
input args
nor an
so is
what I need, or could be something else?


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();.