Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store methods in an array and call them in C#

Tags:

function

c#

.net

In javascript we can do this:

var arr = [];

function fooBar() {
    console.log('Hello World');
}

arr[0] = fooBar;

arr[0]();

Essentially each function is a real object and I can store them in an array if I want to. My question is, since C# doesnt have pointers, what is the best way to handle such as scenario? I mean how can I store function references into arrays?

I know we have something called delegates but im not sure if this is the right thing for the task...

like image 516
Asperger Avatar asked Feb 10 '17 12:02

Asperger


1 Answers

Delegates are exactly what you need:

var list = new List<Action>();

...

void fooBar() {
    ....
}

...

list.Add(fooBar);

The Action is actually nothing but a delegate, simply look its definiton and you´ll see it is similar to a delegate expecting nothing and returning nothing. If you want to pass parameters use any of it´s generic versions, for example Action<T>. If you also need to add methods that return something use the Func-delegate instead.

EDIT: Every delegate has its own type so you can´t mix them and put them alltogether into one single collection, except you use a collection of type Delegate:

var list = new List<Delegate>();

In this case you can´t use urual braces to call the actual delegate, instead you have to use DynamicInvoke and pass the arguments according to the delegates signature.

list[0].DynamicInvoke(args);
like image 146
MakePeaceGreatAgain Avatar answered Oct 20 '22 01:10

MakePeaceGreatAgain