C# delegates tutorial and simple explanation

C# delegates

C# delegates are awesome. What does delegation mean? Delegation, in simple terms, is to hand off a task.

Let’s say John is the CEO and Matthew is a manager who works for John. Daryl and Mary are developers who work for Matthew. CEO John asks Manager Matthew to create for him an desktop application and a web application. Manager Matthew asks Developer Daryl to make a desktop application and Developer Mary to make a web application. In other words, Matthew delegated a task to Daryl and then another task to Mary.

C# delegates do the same thing. Delegates points to a function/method. When the delegate is invoked, it just hands off the effort to the function. There’s a condition. Delegate’s return type and signature (parameters) must match exactly the function it points to. If the function takes string and int as parameters and returns string, delegate must be declared as such also. Let’s take an example.

In this example, we declare a delegate CallAnotherFunction. It returns void and takes one string as  a parameter. This delegate will point to any function that returns void and has a single string as its signature/parameter.

We made two functions that return void and take a string to see how delegate works. We create a delegate variable callFunction and then point it to Function1 We invoke callFunction and provide it a string. Doing so will call Function1 with the string parameter and print “Hi Function1” on the console.

Then, we point callFunction to Function2 and invoke it with a string. Function2 will be invoked with a string parameter and will print “My name is Function2 and I just received this message: Hi Function2” on the console. If you come from a C++ background, delegates are like function pointers.

Let’s take a longer example.

In the above example, we declare a delegate CarDelegate. It will point to any function that returns void and takes boolean as a parameter.

To test it, we create a Car class and create two methods matching the return type and the signature like the delegate expects. Our goal is to tell the Car object what tasks to do. Instead of calling car’s methods directly, we use a single delegate variable and ask it to call car’s methods. We use three methods of doing so.

First example uses the single delegate variable to call both methods of Car object. The second example calls a method that accepts a delegate and boolean as parameters. The third example calls a method that accepts key-value (delegate and boolean) and invokes car’s methods.

Hopefully this will give an easy visualization of delegates. These are very simplistic examples of delegates. MSDN provides exhaustive information about delegates.