Delegates
The .net framework base classes contain a class for dealing with delegates : System.Delegate.
There is also a delegate within the base classes which is System.MultiCastDelegate.
A delegate is used to reference a method. The delegate can be called and it will then run the method it has been assigned. This method can be changed dynamically at run time. When you create a delegate you must however specify the signature of the method which will actually run - that is its return type and parameters.
When you create a delegate it is in fact always a System.MultiCastDelegate. What this means is that MultiCasts can have multiple methods so invoking the delegate can actually run multiple methods.
We will now look at some code to illustrate these ideas. Initially we wil just look at some contrived code pureley to show the syntax etc. After that we will look at a real world example which shows how delegates might be put to good use. It should also be noted that delegates are very important when dealing with events but this will be dealt with in another section.
Delegate Example with 1 method
using System;
Delegate Example with 2 methods
using System;
Ok so the above code samples serve to illustrate the mechanics and syntax of using delegates but to really appreciate their power we need to look at a useful real world example.
Threading springs to mind as an excellent example of when a delegate is used. When we declare a new thread in .net and start that thread it needs to know what to do when it starts - ie what method is used. Therefore we pass into the thread a delegate which references the method we want to run when we start the thread.
The following line for example creates an instance of a thread called myFirstThread. The constructor for the Thread class takes a ThreadStart object as a parameter. The ThreadStart is a delegate and in the constructor for that we pass in the method we want to run.
Thread myFirstThread = new Thread(new ThreadStart(CountForwards));
Some complete code to illustrate this is shown below
using System;
using System.Threading;