What is a Delegate?

A delegate is a type-safe reference to a method with a particular parameter list and return type. It allows methods to be treated as variables and passed as arguments.[^1][^2][^3][^4]

Syntax:

 
public delegate void MyDelegate(string message);
 

This declares a delegate that can refer to any method with a single string parameter and void return type.[^5][^1]


Single-Cast Delegate

A single-cast delegate points to one method at a time. Invoking the delegate executes only the assigned method.[^6][^7]

Example:

 
using System;
 
  
 
public delegate void SingleDel(string msg);
 
  
 
class DelegateTest
 
{
 
    public static void PrintMessage(string msg)
 
    {
 
        Console.WriteLine("Message: " + msg);
 
    }
 
  
 
    static void Main()
 
    {
 
        SingleDel del = PrintMessage;
 
        del("Hello from single-cast delegate!");
 
    }
 
}
 

Only PrintMessage will run when del is invoked.[^1][^6]


Multicast Delegate

Multicast delegates can reference more than one method. When invoked, all methods are called in order. Use + to add methods and - to remove them.[^8][^9][^7]

Example:

 
using System;
 
  
 
public delegate void MultiDel(string msg);
 
  
 
class MultiTest
 
{
 
    public static void First(string msg) { Console.WriteLine("First: " + msg); }
 
    public static void Second(string msg) { Console.WriteLine("Second: " + msg); }
 
  
 
    static void Main()
 
    {
 
        MultiDel del1 = First;
 
        MultiDel del2 = Second;
 
        MultiDel multicast = del1 + del2;
 
  
 
        multicast("Invoked as multicast");
 
        // Output:
 
        // First: Invoked as multicast
 
        // Second: Invoked as multicast
 
    }
 
}
 

All assigned methods are executed.[^9][^7][^8]


Generic Delegates

C# builds in three generic delegates: Func, Action, and Predicate, allowing delegates to be defined without specifying types at compile time.[^10][^11][^12][^13]

  • Func: Takes parameters and returns a value.

  • Action: Takes parameters, void return.

  • Predicate: One parameter, returns bool.

Example:

 
using System;
 
  
 
class GenericExamples
 
{
 
    static void Main()
 
    {
 
        Func<int, int, int> add = (x, y) => x + y;
 
        Console.WriteLine(add(3, 4)); // Output: 7
 
  
 
        Action<string> show = msg => Console.WriteLine(msg);
 
        show("Hello Action!");
 
  
 
        Predicate<string> isShort = str => str.Length < 5;
 
        Console.WriteLine(isShort("cat")); // Output: True
 
    }
 
}
 

Built-in generics simplify code reuse and flexibility.[^11][^13][^10]


Delegates and Events

Events in C# are built on delegates, used to notify subscribers when something occurs. You associate delegates to events; when the event is triggered, all registered methods are called.[^14][^15]

Example:

 
using System;
 
  
 
// Step 1: Declare delegate
 
public delegate void Notify();
 
  
 
// Step 2: Declare event using delegate
 
public class EventPublisher
 
{
 
    public event Notify OnNotify;
 
  
 
    public void TriggerEvent()
 
    {
 
        if(OnNotify != null)
 
            OnNotify();
 
    }
 
}
 
  
 
// Step 3: Subscribe and handle event
 
class EventSubscriber
 
{
 
    public void Handler() { Console.WriteLine("Event received!"); }
 
}
 
  
 
class Program
 
{
 
    static void Main()
 
    {
 
        EventPublisher publisher = new EventPublisher();
 
        EventSubscriber subscriber = new EventSubscriber();
 
  
 
        publisher.OnNotify += subscriber.Handler;
 
        publisher.TriggerEvent(); // Output: Event received!
 
    }
 
}
 

Program 1

using System;
 
delegate double MathOperation(double a, double b);
 
class DelegateExample
{
    public static double Subtract(double a, double b)
    {
        return a - b;
    }
 
    public static double Divide(double a, double b)
    {
        if (b == 0) throw new DivideByZeroException("Cannot divide by zero");
        return a / b;
    }
 
    static void Main()
    {
        MathOperation op;
 
        // Call Subtract method
        op = Subtract;
        Console.WriteLine("Subtraction: " + op(10, 4));  // Output: 6
 
        // Call Divide method
        op = Divide;
        Console.WriteLine("Division: " + op(20, 5));     // Output: 4
    }
}
 

Program 2

  
 
delegate void HandleClick(string name);
class btn
{
    public event HandleClick btnClickedEvent;
    public void Click()
    {
        click();
    }
}
  
 
class Program
{
    static void changeBg(string name)
    {
        Console.WriteLine("Background changed to name : " + name);
    }
 
    static void Main()
    {
        btn btn = new btn();
        btn.btnClickedEvent = changeBg;
        btn.Click();
    }
}

Summary Table

TypeUsageCode/C# Examples
Single-castPoints to one methoddel = MethodA;[^6]
MulticastPoints to multiple methodsdel1 + del2;[^8]
Generic (Func)Built-in, accepts parameters, returns valueFunc<int,int,int>[^10]
Generic (Action)Built-in, accepts parameters, void returnAction<string>[^10]
Generic (Predicate)Built-in, one param, returns boolPredicate<string>[^10]
EventNotify subscribers using delegate, event handlingevent Notify OnNotify;[^14]