Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionaries and Functions

Tags:

c#

dictionary

I have recently begun working with C# and there is something I used to do easily in Python that I would like to achieve in C#.

For example, I have a function like:

def my_func():
 return "Do some awesome stuff"

And a dictionary like:

my_dic = {"do": my_func}

I have made a script in which when the user would input "do", the program would call my_func according to the dictionary.

I'd like to know how I can assign functions to strings in a C# dictionary.

like image 824
Balgy Avatar asked Sep 10 '25 07:09

Balgy


1 Answers

Basically in the same way:

static void Main() {
    var dict = new Dictionary<string, Action>();
    // map "do" to MyFunc
    dict.Add("do", MyFunc);
    // run "do"
    dict["do"]();
}

static void MyFunc() {
    Console.WriteLine("Some stuff");
}
like image 199
Evk Avatar answered Sep 12 '25 20:09

Evk