This blog post is aimed at beginner developers or someone who have just not fully grasped delegates or don’t really understand what problem do they solve and a good example of when they can be used.

What is actually a delegate?

A delegate is a method signature (pretty much a reference to a method) hence it will have to match the signature of the method it wants to reference, an example below:

Let’s say we have a method called MergeCustomerDetails which takes a couple of strings and returns a string, pretty simple:

Now, if we want to use a delegate to call that method we need to create a delegate whose signature matches the signature of the method (that means that the return type and the parameter types must be the same):

If you see the delegate definition above, it matches the MergeCustomerDetails’ method signature (both return a string, and both take 2 arguments of type string). parameter names don’t have to match though (I’ve used different parameter names to highlight that)

The next step is to initialize the delegate and ‘point’ it to the require method:

So instead of calling MergeCustomerDetails we can call our delegate!

When can I use delegates?

We can use delegates whenever we need to pass methods as parameters to another functions so that they can be executed at runtime from there (although a bit complex to grasp an example may be the best way to understand it).

I found the following example in Stack Overflow where there is an excellent use for delegates, which will be explained below. Let’s see the problem and how delegates helped solve it.

We have three functions with the exact same signature (IsChild, IsAdult and IsSenior), if we wanted to execute any of those methods from inside another method we would have to do it manually as there is no way to pass a method as parameter to another method (without using delegate, that is). That would mean writing almost the same code again and again every time we want to call one of the methods.

Fortunately with the use of delegates we can ‘point’ them to those methods and then pass them as parameters.

Let’s start by defining a Person class and the three methods (note that they all have the same method signature):

Now  let’s define a delegate to see how it matches the methods’ signature:

And the method that will take a delegate as parameter:

Finally let’s add the code to the Main function which will call the ‘DisplayPeople’ method passing all the different methods (IsChild, IsAdult and IsSenior)

 

Thanks, any feedback is appreciated !