How to Declare and Use Delegate in C#

If you are learning C#, sooner or later you’ll come across the term delegate. At first, it might sound scary, but don’t worry — delegates are simply pointers to methods. Let’s break it down step by step in the simplest way possible.

✅ What is Delegates in C#?

In simple words, a delegate in C# is like a messenger.

  • It points to a method (or multiple methods).
  • You can call the method(s) indirectly using the delegate.
  • It is type-safe, meaning it ensures the method you point to matches the delegate’s signature (return type + parameters).

Think of it as a remote control. The remote doesn’t know how the TV works, but it knows which button will trigger what action. Similarly, a delegate doesn’t care about the method’s code — it just knows how to call it.


✅ Why Use Delegates in C#?

  1. Flexibility – You can change which method a delegate points to at runtime.
  2. Reusability – Write code once, but plug in different methods later.
  3. Callbacks – Useful when one method needs to notify or call another.
  4. Event Handling – Delegates are the foundation of events in C#.

✅ How to Declare and Use a Delegate in C#

Let’s go step by step with a simple example.

Step 1: Declare a Delegate

// Declaring a delegate that takes two integers and returns an integer
public delegate int MathOperation(int a, int b);

Step 2: Create Methods to Match the Delegate

public class Calculator
{
    public int Add(int x, int y) => x + y;
    public int Multiply(int x, int y) => x * y;
}

Step 3: Use the Delegate

class Program
{
    static void Main()
    {
        Calculator calc = new Calculator();

        // Assign method to delegate
        MathOperation operation = calc.Add;
        Console.WriteLine("Addition: " + operation(5, 3)); // Output: 8

        // Change delegate to another method
        operation = calc.Multiply;
        Console.WriteLine("Multiplication: " + operation(5, 3)); // Output: 15
    }
}

👉 Here, the same delegate was used to call different methods.


✅ Types of Delegates in C#

  1. Single-cast Delegate – Points to one method at a time.
  2. Multicast Delegate – Points to multiple methods at once.
  3. Built-in DelegatesFunc<>, Action<>, Predicate<> (ready-made delegates provided by .NET).

Example of Multicast Delegate:

MathOperation operation = calc.Add;
operation += calc.Multiply; // Now points to both Add and Multiply
operation(5, 3); 
// Calls both methods in sequence (last return value is kept).

✅ Built-in Delegates (Func, Action, Predicate)

Instead of declaring your own delegates, C# provides ready-made ones:

  • Func<T, TResult> – Returns a value.
  • Action<T> – Returns nothing (void).
  • Predicate<T> – Returns a boolean.

Example:

Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(10, 20)); // 30

Action<string> greet = name => Console.WriteLine("Hello, " + name);
greet("C# Learner");

Predicate<int> isEven = num => num % 2 == 0;
Console.WriteLine(isEven(10)); // True

✅ Real-World Example of Delegate in C#

Imagine you are downloading a file, and once it’s finished, you want to notify the user. Instead of hardcoding the notification, you can use a delegate to plug in different actions:

  • Show a message
  • Send an email
  • Write to log

This makes your code more flexible and reusable.


🎯 Delegate in C# Interview Questions

Here are two common delegate in C# interview questions and their detailed answers:


Q1. What is a delegate in C# and why do we use it?

Answer:
A delegate in C# is a type-safe object that can hold references to methods with a specific signature. It is used for callbacks, event handling, and writing flexible and reusable code.

Explanation:
Instead of calling methods directly, we use delegates to pass methods around like parameters. This allows us to change behavior at runtime without rewriting code. Delegates also form the backbone of events in C#.


Q2. Difference between delegate and event in C#?

Answer:

  • A delegate is a reference to a method.
  • An event is a wrapper around a delegate that provides additional control, ensuring only the event owner can raise it.

Explanation:

  • Delegates: Directly callable, can point to multiple methods.
  • Events: Built on delegates but provide a publisher-subscriber model. They are more restricted and secure for real-world applications like GUI or notifications.

Example: Delegates are like the “mechanism,” while events are the “rules” built on top of that mechanism.


Final Tip: Remember, when someone asks you “What is delegates in C#?” — just say: “Delegates are type-safe references to methods. They let us call methods indirectly, enable callbacks, and form the foundation of events in C#.”

cleancode

Top Rated Book In Amazon

Leave a Comment

Your email address will not be published. Required fields are marked *