Delegates

Delegates are fancy. They're hard-coded references to a class of methods that share a signature. "Signature" here meaning methods that have the same return type and argument list. So these methods:

void doingStuff(string, int);
void moreStuff(string, int);
void stuffAndThings(string, int);


All share the same signature: return type == void; argument list contains only two arguments — a string, followed by an integer. So what we can do is create a reference to these kinds of methods (our delegate)

public delegate void ActionJackson(string, int);

Then use it as a parameterized type called ActionJackson. Such as:

ActionJackson toDoList;
toDoList += doingStuff; // Makes "toDoList" call "doingStuff" when given arguments

toDoList("Print ALL the things!", 42);


This will have the effect of calling the doingStuff method, with those two arguments.

Now, this by itself is fairly redundant — I could just call "doingStuff" directly and save myself the trouble! The real power with delegates comes from how you can continue to add methods to be executed when the delegate is called.

toDoList += moreStuff;
toDoList += stuffAndThings;
toDoList("Print ALL the things!", 42);


This time, toDoList will call all three methods in sequence, replacing three lines of code with one. (If you want to remove methods from this list, you can use the -= operator, followed by the method to be removed.)

Now we've arrived at something useful! If you're being a good programmer and partitioning your coding projects into their most atomical parts, then if you run into a need to perform a sequence of method calls, which all share a signature, you can delegate this work (see what I did there?) to a defined delegate! Or even better: write code to dynamically add/remove items to the delegate list to perform any combination of method calls, as dictated by events transpiring in your program!

Like I said at the top of this page: delegates are fancy.