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...
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With