We can explicitly call it in a way every C# programmer should be familiar with:

Int32 y = SomeMethod(5);Console.WriteLine(y);

Using a Delegate...

Now, we may want to wrap this call so we can execute it from somewhere else. This is done through a delegate.

What's a delegate?

A delegate is an object instance that "wraps" a method call (pretty much everything in the .NET framework in an object). An easy way to think of it is as a reference to a method that we can pass around separately from the object that "ownes" the method. In order to "wrap" the method call, the delegate needs two things:

A reference to the instance of the object it will be calling the method on.and

A reference to the method.

To create a delegate we first declare our delegate type. We can think of this as being similar to declaring a new class:

delegateInt32SomeMethodDelegate(Int32 input);

And then we can use an instance of this delegate to "wrap" our method call:

Using the same method we had earlier...

staticInt32 SomeMethod(Int32 input){return input + 1;}

Somewhere else in our code we can instantiate the delegate as follows. (note: in the sample below, "Program" is a static class)

// f is a delegate object that "wraps" the callSomeMethodDelegate f = newSomeMethodDelegate(Program.SomeMethod);

Now we can use our delegate instance to call the same method.

Int32 y = f(5);

The compiler is smart enough to figure out which kind of delegate to instantiate so we can use a shorter syntax if we want. We are actually still very explicitly instantiating a delegate by telling the compiler what kind of delegate we want with the declaration on the left hand side of the assignment operator. (note: I don't need to specify the object in the following code sample because the delegate instantiation is in the same class as "SomeMethod()".)

// f is a delegate object that "wraps" the callSomeMethodDelegate f = SomeMethod;

Adding Generics in the Mix....

We may not need a bunch of explicit delegate types lying around in our project (although sometimes it is good to have a few for more readable code) and can use generics to consolidate all delegates with similar surface areas (the same input and output types):

We also have the generic Action<> delegate which wraps a method with no return value and a Predicate<> delegate which is usually used to perform tests returns a Boolean and a Comparison<> delegate to compare two objects.

Anonymous Delegate....

We may want to have a method that does not belong to a class (which is why we call it anonymous) and can declare it in-line using the following syntax. Notice how the method has no "outer shell" definition. The "SomeMethodDelegate" object is still instantiated and points to the in-line method.

If you haven't done it already, it is worth taking some time and using the debugger to step through code containing anonymous method to get a better understanding of how the execution of the code flows.

Closures...

One of the ultra-cool features of anonymous methods is that they support closures which is a concept coming out of functional programming languages. Closures are VERY powerful and can help us keep code more concise. When a language supports closures it basically means that the a method body has access to any local variable declared outside it's scope.

The syntax for declaring an anonymous delegate is pretty verbose (and kind of ugly). With the 3.5 Framework, we have a much shorter (and nicer) way to instantiate anonymous delegates using lambda expressions.

SomeMethodDelegate f = x => { return x + 1; };Int32 y = f(5);

The input parameter is the variable before the => symbol.

x => { return x + 1; };

The body of the method is what appear after the => symbol.

x => { return x + 1; };

Because the "SomeMethodDelegate" signature says we have to input a Int32 and output an Int32, the compiler knows that our "x" variable should be an integer (see if makes more sense if you try and match the delegate signature (below) up with our lambda expression (above).

delegateInt32SomeMethodDelegate(Int32 input);

We can use an even shorter syntax for declaring simple anonymous methods with the lamba expression and leave off the brackets and the "return" keyword. The following code uses the simpler syntax:

Of course we can use lambda expressions with generic delegates as well. The following shows the lambda expression syntax for instantiating a generic delegate with two input parameters. If our delegate has multiple input parameters, we must group them in parenthesis:

Func<Int32, Int32, Int32> add = (m, n) => m + n;Int32 y = add(3, 4);

What Are They Good For?

Delegates are used most frequently for subscribing to events so we'll look at how we can utilize delegates with an object that exposes an event.

Here is our dummy event raising object which could just as easily be a UI form or control.

There are also many other places where delegates can be useful. Another scenario is when we need to pass a delegate to another method for execution. See if you can figure out what's happening in the following code.

If we have a method declared that accepts a delegate and another item defined as its input parameters, it will execute the method using the second parameter as input.