Delegates in C#

Delegates are used in C# if for some reason you want to pass methods as parameters.

For example:

You have the number 10 and you want to print it out in several different formats. You might have several different methods to do this:

  • A method to print it as a whole number
  • A method to print it as monetary currency with a pound, euro or dollar sign.
  • A method to print it as a decimal

Fine… The thing that those those methods all have in common is that they take in the integer and do something with it. In this case the integer we pass will be 10, but by design it would probably be better if the methods can accept any integer eg. public void PrintAsMoney(int){}

We could create a delegate called PrintValue

public delegate void PrintValue(int value);

And that delegate can later be used in a method to represent the three methods

PrintValue printDelegate=PrintAsInt;
printDelegate+=PrintAsMoney;
printDelegate+=PrintAsDecimal;

We’ve now set which methods should be used when printDelegate is invoked. We already know that all those methods are compatible with our delegate because they can all accept an int.

So… let’s invoke the delegate

printDelegate(10);

Our program knows which methods to use and to pass the number 10 to, because we just specified that when we set the methods for printDelegate. So all in one clean swoop it passes the number 10 to each of those methods that were subscribed to the delegate and the required data is printed. This is a multicast delegate because it uses more than one method. A standard delegate will only pass one method but works pretty much the same way.