DEV Community

Hamza
Hamza

Posted on • Edited on

Explaining the Delegates Concept !

Delegates are the type that defines a method signature, and can hold a reference to one or more methods with that signature.
They are often described or called as a Type-Safe function pointers because they allow methods to be passed as a parameter, assigned to variable, or invoke dynamically all while ensuring type-safe..πŸ”’

What are the Key Points of the Delegates πŸ—οΈ ?

  • Method Signature : A delegate specifies return type and the parameters of the method it can refer to.

  • Type-Safe : Delegates ensures that the method they reference has the correct signature.

  • Multicast : A single delegate can reference multiple methods and invoke them sequentially. This is known as multicast delegate.

  • Encapsulation : Delegates encapsulates the methods and it's behavior making them useful for defining callback mechanism.

So what is the Syntax of Delegates ?!

// 1. Declare a Delegate..
public delegate void MyDelegate(string message);

// 2. Create a method matching the Delegate's signature
public class Program {

  public static void DisplayMessage(string message) {
    Console.WriteLine(message);
  }

  public static void Main() {
    // 3. Instantiate the delegate
    MyDelegate del = DisplayMessage;

    // 4. Invoke the delegate
    del("Hellow, World!");
  }

}
Enter fullscreen mode Exit fullscreen mode

Let's talk about the common uses !
There are 3 common uses :

  1. Event Handling
  2. Callback mechanism
  3. LINQ and Functional programming

Let's explain them one by one

1- Event Handling : Delegate are the foundation of events in C#, They allow subscribing and unsubscribing to events using methods.

public delegate void Notify();

public class EventExample {
  public event Notify OnNotify;

  public void TriggerEvent() {
    OnNotify?.Invoke(); // Safely invoke the delegates if it has subscribers 
  }
}
Enter fullscreen mode Exit fullscreen mode

2- Callback mechanism : Passing a method to another method to be executed later.

public class Calculator {
  public void PerformOperation(int x, int y, Action<int> callback) {
    int result = x + y;
    callback(result);
  }
}

public class Program {
  public static void Main() {
    Calculator calc = new ();
    calc.PerformOperation(2, 3, Console.WriteLine); // Pass Console.WriteLine as a Delegate
  }
}
Enter fullscreen mode Exit fullscreen mode

3- LINQ and Functional Programming : Delegates like Func, Action, Predicate are heavily used in LINQ to define custom logic.


What are the built-in Delegates ??

  1. Action : Represents method with no return value but with parameters.
Action<string> print = Console.WriteLine;
print("Hello, World!");
Enter fullscreen mode Exit fullscreen mode
  1. Func : Represents a method with a return value and parameter.
Func<int, int, int> add  (x,y) => x + y;
Console.WriteLine(add(3,4));
Enter fullscreen mode Exit fullscreen mode
  1. Predicate : Represents a method that return bool and it takes a single parameter.
Predicate<int> IsEven = x => x % 2 == 0;
Console.WriteLIne(IsEven(4));
Enter fullscreen mode Exit fullscreen mode

Advantages of Delegates

  • Flexibility => Enables dynamic methods invokation

  • Loose Coupling => Promotes code extensibility by allowing methods to be assigned dynamically

  • Reuseability => Encourages creating modular and reuseable code

That's it for now! Keep coding and stay awesome. Catch you later Nerds!

Top comments (0)