Author - Dave Amour

Dave Amour has used computers for as long as he can remember and intially started out as an IT trainer delivering a range of IT courses but for the last 11 years has been focusing on the arena of web application development. He was worked for numerous companies over the years and is currently working for Audacs Software Ltd. Dave is also a keen squash player and an active and sucessful member of Experts Exchange

Please feel free to submit any constructive comments which you can do at the bottom of this page.

Dave may be available for programming tuition or consultancy work. Contact via dave@audacs.co.uk
Dave Amour - Click to view CV 

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; 

namespace Delegates
{
    class DelegatesTest
    {
        public delegate void myDelegate();
 
        [STAThread]
        static void Main(string[] args)
        {
            myDelegate myDeleGateInstance = new myDelegate(OutputHello);
            myDeleGateInstance();
            Console.Read();
        }
 
        public static void OutputHello()
        {
            Console.WriteLine("Hello");
        }
    }
}

Delegate Example with 2 methods

using System; 

namespace Delegates
{
    class DelegatesTest
    {
        public delegate void myDelegate();
 
        [STAThread]
        static void Main(string[] args)
        {
            myDelegate myDeleGateInstance = new myDelegate(OutputHello);
            myDeleGateInstance += new myDelegate(OutputGoodbye);
            myDeleGateInstance();
            Console.Read();
        }
 
        public static void OutputHello()
        {
            Console.WriteLine("Hello");
        }
 
        public static void OutputGoodbye()
        {
            Console.WriteLine("Goodbye");
        }
    }
}


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; 

namespace ConDelegates
{
    class ThreadExample
    {
        [STAThread]
        static void Main(string[] args)
        {
            Thread myFirstThread = new Thread(new ThreadStart(CountForwards));
            Thread mySecondThread = new Thread(new ThreadStart(CountBackwards));
 
            myFirstThread.Start();
            mySecondThread.Start();
 
            Console.WriteLine("Hit Enter to stop the threads\n\n");
 
            Console.ReadLine();
            Console.WriteLine("\nStopping Thread 1\n");
            myFirstThread.Abort();
 
            Console.ReadLine();
            Console.WriteLine("\nStopping Thread 2\n");
            mySecondThread.Abort();
        }
 
        public static void CountForwards()
        {
            int counter = 0;
 
            while (true)
            {
                Console.WriteLine("myFirstThread: " + counter.ToString());
 
                counter++;
 
                Thread.Sleep(1000);
 
            }
        }
 
        public static void CountBackwards()
        {
            int counter = 0;
 
            while (true)
            {
                Console.WriteLine("mySecondThread: " + counter.ToString());
 
                counter--;
 
                Thread.Sleep(1000);
 
            }
        }
    }
}

Leave a comment

Name

Email (optional and not disclosed)



Email address is not disclosed but just used to alert you of new posts if entered
Word CV
HTML CV
PDF CV
Text CV
CMS Lite
ETraining
Planet Health
Florida Health
the Date Shack
Taylors
Emcat
Emtex
Browne Jacobson
Alliance & Leicester
Baird Leisure
Swarfega
Creature Comforts
Rugeley Chess Club
Katnip
Katmaid
Dudley NHS
Contact Me
Current Status