.Net application development specialists
asp.net, c#, vb.net, html, javascript, jquery, html, xhtml, css, oop, design patterns, sql server, mvc and much more
contact: admin@paxium.co.uk

Paxium is the company owned by myself, Dave Amour and used for providing IT contract development services including


  • Application development - Desktop, Web, Services - with Classic ASP, Asp.net WebForms, Asp.net MVC, Asp.net Core
  • Html, Css, JavaScript, jQuery, React, C#, SQL Server, Ado.net, Entity Framework, NHibernate, TDD, WebApi, GIT, IIS
  • Database schema design, implementation & ETL activities
  • Website design and hosting including email hosting
  • Training - typically one to one sessions
  • Reverse Engineering and documentation of undocumented systems
  • Code Reviews
  • Performance Tuning
  • Located in Cannock, Staffordshire
Rugeley Chess Club Buying Butler Cuckooland Katmaid Pet Sitting Services Roland Garros 60 60 Golf cement Technical Conformity Goofy MaggieBears Vacc Track Find Your Smart Phone eBate Taylors Poultry Services Lafarge Rebates System Codemasters Grid Game eBate DOFF

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);
 
            }
        }
    }
}