Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# dictionary method as a value

I have a class with a bunch of methods in it, the methods transfer variables elsewhere in my program when called. I want to use a dictionary as the middle man between the methods that transfer data and the methods that call them.

So here is my question. Say I make a dictionary, where the key is an int and I want the value to be the name of a method. I will assign a new value / method each time I add to the dictionary. Is there a value type I can put there that will let me do this?

Dictionary<int, ?> methodKey= new Dictionary<int, ?>();

I tried to find a list of types that dictionary will take but I couldn't find anything specific.

Thanks in advance

like image 783
AmazingMrBrock Avatar asked Mar 24 '26 11:03

AmazingMrBrock


1 Answers

Use any delegate type as a type of value. For example:

Dictionary<int, Action>

So, you'll be able to write such things:

        dictionary[0] = () => Console.WriteLine("0");
        dictionary[1] = Foo;
        dictionary[2] = a.Bar;

Specific delegate type depends on your needs - may be, you want for methods to have some input parameters or output/return values, but it should be most common type.

like image 119
Dennis Avatar answered Mar 26 '26 23:03

Dennis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!