Understanding C# Delegates: Function Pointers and Event Handling

Learn about C# delegates—type-safe references to methods. This guide explains delegate declaration, usage, and their role in event handling and passing methods as parameters, enhancing your C# programming skills.



Understanding C# Delegates

In C#, a delegate is a reference type variable that holds a reference to a method. Think of it as a function pointer, but it's object-oriented, type-safe, and more secure than traditional function pointers.

Delegates: Methods as Variables

A delegate acts like a variable that can store a reference to a method. This allows you to pass methods as arguments to other methods or treat methods like data.

Delegate Declaration

A delegate is declared using the `delegate` keyword, specifying the return type and parameters of the methods it can hold. Internally, a delegate declaration defines a class that inherits from `System.Delegate`.


// Delegate declaration: takes an int and returns an int
delegate int MyDelegate(int x);

Example: Using Delegates

This example demonstrates a delegate that holds references to two methods (`add` and `mul`) and then invokes them.


using System;

public class DelegateExample {
    // ... (add, mul, getNumber methods) ...

    public static void Main(string[] args) {
        MyDelegate c1 = new MyDelegate(add); // Assign add method to the delegate
        MyDelegate c2 = new MyDelegate(mul); // Assign mul method to the delegate
        // ... (calling methods using the delegate) ...
    }
    // ... (add, mul, getNumber methods) ...
}

Explanation

The `add` and `mul` methods are assigned to the `MyDelegate` instances `c1` and `c2`. The methods are then invoked using the delegates, demonstrating how delegates enable treating methods as data.