Home About

November 18th, 2008

Using Delegates in C# - 1

What is a delegate and why would you want to use them?

Calling methods with parameters comes natural in programming, but what if you would like to pass the methods themselves to another method?

To give an example: You might want to set a timer and have the timer call a particular method when the time comes. To avoid having to hard code each possible action together with its own timer you might want to pass the action method in your call to the timer itself. In C# this is called delegation.

Another use for delegation is in sort routines. The actual sorting code is common, but the action that decides which element comes before another depends on what you are trying to sort. In this situation you could pass a method to the sorting routine that provides this knowledge.

A pseudo code example for sorting an array of integers:

Int[] A;

int LargerThan1( int C, int D )
{
   return (C > D);
}

int LargerThan2( int C, int D )
{
   if (Today == TuesDay) return (D > C);
   return (C > D);
}

QuickSort( A[] , LargerThan1 );
QuickSort( A[] , LargerThan2 );  // Same, but with a twist on Tuesdays

Delegation comes in handy when you need to call different methods from inside other methods. This is quite common in event driven programmes (such as the above timer example).

There are some drawbacks to delegation however:

  • The implementation of a delegate must be static.
  • Because of this delegates cannot call other methods or properties of the object that implements them.

The following code shows the minimal implementation of a delegate. The code defines a delegate, and two implementations. It then calls a method, passing each implementation of the delegate method in turn.

using System;

namespace DelegateDemo1
{
    class MainClass
    {

        // Delegate_Example
        //
        // To create a delegate we need to define a method. Important are the
        // return type, name of the delegate and the parameters.

        public delegate void Delegate_Example(string message);

        // DelegateModel_A
        //
        // This method exactly follows the delegate model (return type: void and one string parameter)
        //
        // An implementation of the delegate can only be static. 

        public static void DelegateModel_A(string message)
        {
            Console.WriteLine("Model_A: {0}",message);
        }

        public static void DelegateModel_B(string message)
        {
            Console.WriteLine("Model_B: {0}",message);
        }

        // Example_method
        //
        // This method accepts our Delegate as a parameter, and calls it in turn.
        // Normally this routine would perform a sort action, or something similar
        // that would need the delegate to perform some action.

        public static void Example_method(Delegate_Example E)
        {
            // Here we do some magic

            // We call the method passed to us
            E("Hello World");

            // Here we do some more magic

        }

        static void Main()
        {
            // We can assign the implementation methods like below
            Delegate_Example A = DelegateModel_A;
            Delegate_Example B = DelegateModel_B;

            // Then we pass them to a method that knows how to call this delegate
            Example_method(A);
            Example_method(B);
        }

    }

}
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google
  • Reddit

Tags: , , ,

One Response to “Using Delegates in C#”

  1. Creating and synchronizing Threads with C# | Dijksterhuis.Org Says:

    [...] ThreadStart object mentioned in the Thread constructor is actually a delegate. It defines the format that the entry point function should follow : a function returning [...]

Leave a Reply


Recent Comments
  • Ales: Hi, Thanks for the code… I must say I did not experience any errors decrypting any of my messages. I even...
  • JC: Thanks very useful and well explained
  • Thomas: This is a public static class written in the C# language that does not save state. You can call into the...
  • Simon: Thank you very much for this post! It helped me essentially to overcome obstacels to work with mono!
  • Graham: This is a good research for keyboard shortcuts! Some shortcuts are also compatible for Windows OS. I have...