Delegates in C#

One way to think about a delegate is like a reference to a function. For example, say you have a button in a window, and you want something to happen when the button is clicked. You can attach a delegate to the Click event of the button, and whenever the user clicks this button, your function will be executed.

class MyWindow : Window
{
    Button _button;

    public MyWindow()
    {
        _button = new Button();
        // place the button in the window
        _button.Click += MyWindow.ButtonClicked;
    }

    static void ButtonClicked(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Button Clicked");
    }
}

Notice how I make ButtonClicked a static function - I want to make a point about non-static functions next. Suppose instead that ButtonClicked is a non-static member:

class MyWindow : Window
{
    Button _button;
    int _numClicked = 0;

    public MyWindow()
    {
        this._button = new Button();
        // place the button in the window
        this._button.Click += this.ButtonClicked;
    }

    void ButtonClicked(object sender, RoutedEventArgs e)
    {
        this._numClicked += 1;
        MessageBox.Show("Button Clicked " + this._numClicked + " times");
    }
}

Now the delegate contains both a reference to the function "ButtonClicked" and the instance, "this", which the method is called on. The instance "this" in the MyWindow constructor and "this" in ButtonClicked are the same.

This is a specific case of a concept known as closures which allows "saving" the state - the current object, local variables, etc. - when creating a delegate. In the above example, we used "this" from the constructor in the delegate. We can do more than that:

class MyWindow : Window
{
    Button _button;
    int _numClicked = 0;

    public MyWindow(string localStringParam)
    {
        string localStringVar = "a local variable";
        this._button = new Button();
        // place the button in the window
        this._button.Click += new RoutedEventHandler(
            delegate(object sender, RoutedEventArgs args)
            {
                this._numClicked += 1;
                MessageBox.Show("Param was: " + localStringParam + 
                     " and local var " + localStringVar +
                     " button clicked " + this._numClicked + " times");
            });
    }
}

Here we created an anonymous delegate - a function which is not given an explicit name. The only way to refer to this function is using the RoutedEventHandler delegate object. Furthermore, this function exists in the scope of the MyWindow constructor, so it can access all local parameters, variables, and the member instance "this". It will continue to hold references to the local variables and parameters even after the MyWindow constructor exits.

As a side note, the delegate will also hold a reference to the object instance - "this" - even after all other references to the class a removed. Therefore, to ensure that a class is garbage collected, all delegates to a non-static member method (or delegates created in the scope of one) should be removed.


Well, a delegate is a type. The variables of a delegate type can reference, or point to, a function.

This gives you an indirect way to call a method, so methods can be selected at runtime. And thus you can have variables, parameters and properties containing a method. The properties are called events.

Just one more code sample, to be complete:

   delegate void ADelegate();  // the delegate type

   void Foo() { ... }   // a compatible method
   void Bar() { ... }   // a compatible method

   void Main()
   {
      ADelegate funcPtr;  // a delegate variable

      if (aCondition)
        funcPtr = Foo;  // note: _not_ Foo(), Foo is not executed here
      else
        funcPtr = Bar;

      funcPtr(); // calls Foo or Bar depending on aCondition
   }

Use of delegate variables is not common. But you can use a delegate parameter to for instance a Sort method to select an ascending or descending sort.

  delegate int Compare(MyClass a, MyClass b);  // the delegate type

  void int CompareUp(MyClass a, MyClass b) { ... }   
  void int CompareDn(MyClass a, MyClass b) { ... }   

  void Sort(MyClass[] data, Compare comparer) { ... }

And you probably know events, which are (a special kind of) properties based on delegates.


1) First you have to understand why/when you need a delegate, what is the problem that it solve.

In my experience I mainly use them to allow a user to customize an object's behavior.

Immagine a Grid component that allows the developer to customize how each column will be rendered. For example you want to write a of red color value when it's a number under zero.

The developer that create the Grid does not know how the user want to customize the output so it need a mechanism that let the user of the component to inject some logic into the component.

2) Then you have to understand how the delegate works

What is confusing is the strange code you have to write to do so, and the many ways you have to do the same thing.

This is the grid class:

// the grid let the programmer that will use it to customize the output
public class Grid{

    // 1) First I declare only the interface of the delegate
    public delegate String ValueFormatterDelegate(String v);

    // 2) I declare a handler of the implementation of the delegate
    public ValueFormatterDelegate ValueFormatterHandler; 

    // 3) I call the handler inside the Print method
    public void Print(String x){
        Console.WriteLine( ValueFormatterHandler.Invoke(x) );
    }

}

// 1) First I declare only the interface of the delegate public delegate String ValueFormatterDelegate(String v);

Note that is like a normal method but:

  • it has a delegate keyword
  • it don't has a implementation

In this way I say: "the method that will format the output has this interface: it will take a string as input and it will output a string"

It remember to me a definition of a method of an interface.

// 2) I declare a handler of the implementation of the delegate public ValueFormatterDelegate ValueFormatterHandler;

Now I have to create a property of the type of the delegate that will handle te implementation of this method.

// 3) I call the handler inside the Print method public void Print(String x){ Console.WriteLine( ValueFormatterHandler.Invoke(x) ); }

Inside the Print method I can use the handler that will link the real implementation.

ValueFormatterHandler is of type ValueFormatterDelegate and ValueFormatterDelegate is ad delegate and .Invoke is a method of delegate type

This is a program that use my Grid class and is able to personalize it on the fly. The problem here is the many ways you have to do the same thing.

using System;

public class Program{
    public static void Main(){

        var printer = new Printer();

        // METHOD 1 : link to a named method
        // here i link the handler of the delegate to a real method
        // the FormatXXX is a static method defined at the ed of this code
        printer.ValueFormatter = FormatXXX;

        // when i call Print("hello")
        printer.Print("hello"); // XXhelloXX

        // METHOD 2 : anonimous method
        // think at this like a method but without a name
        // FormatYY (String x ){ return "YY"+x+"YY"; };
        //  become
        // delegate (String x ){ return "YY"+x+"YY"; };
        printer.ValueFormatter = delegate (String x ){ return "YY"+x+"YY"; };
        printer.Print("hello"); // YYhelloYY

        // METHOD 3 : anonimous method using lambda
        // as you can note the type of parameter x is inferred from the delegate declaration
        // public delegate String ValueFormatterDelegate(String v);
        printer.ValueFormatter = (x)=>"KK" + x + "KK";

    }

    public static String FormatXXX(String y){
        return "XX"+ y +"XX";
    }

}

Tags:

C#

Delegates