C# Delegate

Overview

  • Delegate defines a function signature
  • Delegate is a place holder for a future function
  • Delegate is an object
    • Need to be instantiated before being used
    • Can be passed around like an object

Define a simple delegate

  • // Define a delegate for fxn signature
    public delegate 
      void SwapItems(
      ref string str1, ref string str2);
     
    // Example class
    public class MySwapClass {
      // Define a conforming method 
      public void MySwapFxn(
        ref string str1, ref string str2){
        // Implementation
      }
     
      // Use delegate as parameter
      public void SortItems(
        string[] items, SwapItems fxn){
        fxn(items[0], items[1]);
      }
     
      // Run
      public static void Main()
      {
        MySwapClass msc = new MySwapClass();
        // Construct a delegate object
        SwapItems myswapfxn = new SwapItems(
          msc.MySwapFxn);
        // Items to sort
        string[] items = {"one", "two"};
        // Pass delegate object
        msc.SortItems(items, myswapfxn);
      }
    }

Define a multicast delegate

  • // Define a multicase delegate
    // Need to be a void return type
    public delegate void MyDelegate();
     
    // Class using delegate
    public class DelegateConsumer
    {
      // Delegate object
      public MyDelegate md;
     
      // Constructor
      public DelegateConsumer()
      {
      }
     
      // Invoke delegate
      public void InvokeDelegate()
      {
        if (md != null)
        {
          md();
        }
      }
    }
     
    // Handlers
    public class MyDelegateHandlers
    {
      public static void Handler1()
      {
        Console.WriteLine(
          "Invoking Handler1...");
      }
     
      public static void Handler2()
      {
        Console.WriteLine(
          "Invoking Handler2...");
      }
    }
     
    // Test run
    public class TestMulticastDelegate
    {
      public static void Main()
      {
        DelegateConsumer dc = 
          new DelegateConsumer();
        MyDelegate d1 = new MyDelegate(
          MyDelegateHandlers.Handler1);
        MyDelegate d2 = new MyDelegate(
          MyDelegateHandlers.Handler2);
        dc.md += d1;
        dc.md += d2;
        dc.InvokeDelegate();
      }
    }
This entry was posted in c#. Bookmark the permalink.