C# Delegates – Part 1

A delegateis a type that references a method. Once a delegateis assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value… ~ MSDN

If you still don’t get it, I’ll break it down even more…

In Depth Look

A delegate is someone (or something) designated to act for or represent someone (or something) else. When coding, a delegate represents a defined method. A great example for using delegates is a simple calculator.

Calculator Scenario

Say you want to perform an operation on two numbers, x and y. That operation can be addition, subtraction, multiplicationor division. The parameters are the same no matter which type of calculation you want to perform.

Mathematical Operations

C#

1

2

3

4

z=x+y;

z=x-y;

z=x*y;

z=x/y;

The only difference in the above code is the operator that’s used. That being the case, what if we could call one method and pass in a parameter telling us which operator to use? That’s where delegates come into play.

Delegates represent Methods

Let’s define a delegate and the methods that it will represent:

1

2

3

4

5

privatedelegate doubleCalculateDelegate(doublex,doubley);

privatedoubleAdd(doublex,doubley){returnx+y;}

privatedoubleSubtract(doublex,doubley){returnx-y;}

privatedoubleMultiply(doublex,doubley){returnx*y;}

privatedoubleDivide(doublex,doubley){returnx/y;}

As you can see, the method definitions and the delegate method look the same except for the delegate keyword in front of the return type. Think of the delegate method as a template of the type of method in which it can call. For instance, a delegate method with a return type of string can only represent a method with the return type of string. Also notice that the delegate method looks like a normal method except that it has no method body. That’s because it’s going to call the body of the method that it’s referencing. But how does a delegate know which method to call?

Calling all methods!

You have to decide which method the delegate will call by assigning that method to the delegate. Let’s say I want to call the Add() method. Let’s instantiate a delegate variable:

1

privateCalculateDelegate calculate=newCalculateDelegate(Add);

The delegate variable calculate now represents the Add() method. So now when you call:

1

doubleresult=calculate(3,5);

the variable result will equal 8.

Why not just call the Add() method!?!

Well, you could. This is what I was thinking, at first, until I realized that delegates are very powerful, especially when used as a Callback or with Anonymous Methods. But I’ll save that for another article.