Skip to content

Delegates C#

A Delegate by definition is a person sent or authorized to represent others.
The key concept here is ‘Represent others’. Delegates are used to represent other methods.

Delegates at work

Start by looking the example below, this is how we declare a simple Delegate.

public delegate int AddNumbersDelegate(int a, int y)

It is just like any other variable but instead of holding an integer value, it holds
a method that can be executed.

Now that we have declared our delegate we associate
any method from any class as long as it matches the signature and the return type of
the delegate. The method below is a valid one

public int AddNumbers(int a, int b)
{
 return a + b;
}

Finally we assign the actual method (AddNumbers) to our delegate

AddNumbersDelegate delegateHandler = AddNumbers;

We can then call our delegate witch in turn will call the AddNumbers method

delegateHandler(1,2);

Delegates are also used to pass methods, as arguments to other methods
so here is a very intersting example where a caller’s function code
becomes part of the callee.

public string AddWithMsg(string msg, int a, int b, AddNumbersDelegate callback)
{
 return msg + " " + callback(a,b).ToString();
}
AddWithMsg("The result is: ", 2, 2, delegateHandler);

And the output is
The result is: 4

Summary

I know what you are probably thinking right now…This seems pretty useless Nick!!! Well i think it is!!! Just kidding!
No it is not useless at all, it is just something you will not use all the time. Of course delegates are something
relativly new and you can create anything you want without ever using them. However they can prove to be a
very handy tool that can decouple your code
.
Every project and situation is diffrent so use them wisely!

To see delegates at work, clone or download a full working example here. Also check the next article on Anonymous Methods to see how you simplify syntax and make them easier to work with.
Finally you can always Buy me a coffeeBuy me a coffee and help me stay awake to continue my excavations!

0

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *