0
0
CsharpHow-ToBeginner · 3 min read

How to Use Delegate in C#: Simple Guide with Examples

In C#, a delegate is a type that holds references to methods with a specific signature. You use it by declaring a delegate type, creating an instance pointing to a method, and invoking it like a normal method.
📐

Syntax

A delegate declaration defines a method signature. You create an instance of the delegate by assigning it a method that matches this signature. Then you call the delegate instance to invoke the method.

  • delegate: keyword to declare a delegate type
  • ReturnType: the return type of the method
  • DelegateName: the name of the delegate type
  • Parameters: the input parameters of the method
csharp
public delegate void MyDelegate(string message);

// Usage:
MyDelegate del = MethodName;
del("Hello");
💻

Example

This example shows how to declare a delegate, assign a method to it, and invoke it. The method prints a message to the console.

csharp
using System;

public class Program
{
    // Declare a delegate type that takes a string and returns void
    public delegate void PrintMessage(string message);

    // Method matching the delegate signature
    public static void ShowMessage(string msg)
    {
        Console.WriteLine("Message: " + msg);
    }

    public static void Main()
    {
        // Create delegate instance pointing to ShowMessage
        PrintMessage printer = ShowMessage;

        // Invoke the delegate
        printer("Hello, delegate!");
    }
}
Output
Message: Hello, delegate!
⚠️

Common Pitfalls

Common mistakes when using delegates include:

  • Assigning a method with a different signature than the delegate type.
  • Forgetting to instantiate the delegate before invoking it, causing a NullReferenceException.
  • Not using += to add multiple methods to a delegate invocation list.

Always ensure the method signature matches exactly and check for null before calling the delegate.

csharp
using System;

public class Program
{
    public delegate void MyDelegate(string msg);

    public static void WrongMethod(int number)
    {
        Console.WriteLine(number);
    }

    public static void CorrectMethod(string msg)
    {
        Console.WriteLine(msg);
    }

    public static void Main()
    {
        MyDelegate del;

        // Wrong: method signature does not match delegate
        // del = WrongMethod; // This causes a compile error

        // Correct assignment
        del = CorrectMethod;

        // Null check before invoking
        if (del != null)
        {
            del("Safe call");
        }
    }
}
Output
Safe call
📊

Quick Reference

Remember these quick tips when working with delegates:

  • Delegate types define method signatures.
  • Assign methods with matching signatures to delegates.
  • Use delegateInstance() to invoke.
  • Use += to add multiple methods to a delegate.
  • Always check for null before invoking.

Key Takeaways

A delegate holds references to methods with a specific signature and can be invoked like a method.
Always match the method signature exactly when assigning to a delegate.
Check for null before calling a delegate to avoid runtime errors.
Use += to add multiple methods to a delegate's invocation list.
Delegates enable flexible and reusable method calls in C#.