This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Delegates Introduction


In this article we are going to discuss how to implement delegates with examples in C#.

Delegate Introduction

  1. Delegates are type-safe function pointer. This means the method signature of the delegate and the method it points to must match.
  2. A delegate hold the reference of a method and then call the method for execution.
  3. Delegates are similar to function pointers in C and C++, but are type-safe and secure.
  4. A delegate can refer to more than one methods of same return type and parameters.
  5. They are used to pass methods as arguments to other methods, and are typically used for defining callback methods and event handlers.

Example

Companies send their delegates to conferences to represent their products(because CEO might be busy with other things).

The CEO defines certain responsibilities to delegates (in advance)

  1. What has to be done  (in programming world function)
  2. What he should talk  (say parameter)
  3. Collect feedback or get new customers (return value).

Now the CEO select one delegate for the conference when needed (say at run time).

Advantages of Delegates

  1. Type Safety - Delegates are type-safe. This means the method signature of the delegate and the method it points to must match.
  2. Encapsulation - Delegates can be used to encapsulate a method call, making it possible to pass methods as arguments to other methods.
  3. Anonymous Methods and Lambda Expressions - Delegates can reference anonymous methods or lambda expressions, providing flexibility and convenience.
  4. Multicasting - Delegates can reference more than one method. When invoked, all the methods the delegate references are called.

Why Use Delegates

  1. Event Handling - Delegates are commonly used to implement event handling in C#. They provide a way to notify objects of events and allow for the separation of event-handling code from the core logic.
  2. Callback Methods - Delegates enable callback methods. A method can be passed as a parameter to another method, which can then call the passed method at an appropriate time.
  3. Decoupling - Delegates allow methods to be passed and stored without the caller needing to know which method will be called. This helps decouple components and make the code more modular and flexible.
  4. LINQ and Functional Programming - Delegates are fundamental to LINQ (Language Integrated Query) and functional programming techniques in C#. They allow for passing functions as parameters, enabling more expressive and readable code.

Types of Delegate

  1. Single Delegate
  2. Multicast Delegate

1. Single Delegate

Steps to declare and use a delegate in C#

To call a method by using a delegate we have three steps. Here is a basic example of how to declare and use a delegate in C#:

1. Declaring a delegate

This declaration defines a delegate named AddDelegate that can reference any method that takes a two int parameter and returns void.

public delegate void AddDelegate(int a, int b);

2. Defining methods that match the delegate signature

Now the point is delegate and function type and parameter should be same type. That is the reason why delegate say type safe function pointer.

public void Add(int a, int b)
{
  Console.WriteLine(a + b);
}

3. Instantiating and using the delegate

AddDelegate ad = new AddDelegate(prog.Add);
ad(10, 30)
//ad.Invoke(20, 30);

Example

using System;

namespace delegateproject
{
    public delegate void AddDelegate(int a, int b);
    public delegate string SayDelegate(string str);
    class Program
    {
        public void Add(int a, int b)
        {
            Console.WriteLine(a + b);
        }
        public static string SayHello(string name)
        {
            return "Hello " + name;
        }
        static void Main()
        {
            Program prog = new Program();
            AddDelegate ad = new AddDelegate(prog.Add);
            ad(10, 30);
            ad.Invoke(20, 30);
            SayDelegate sd = new SayDelegate(Program.SayHello);
            string str = sd("Rohatash");
            string str1 = sd.Invoke("Rahul");
            Program.SayHello(str);
            Console.WriteLine(str);
            Console.WriteLine(str1);
            Console.ReadLine();
        }
    }
}

Output

Delegates in C#

2. Multicast delegates

It holds the references of more than one method. When a multicast delegate is invoked, it calls each of its assigned methods in the order they were added. To combine the delegates we can use the + operator.

Notification System with Multicast Delegates

Let's see a scenario where we have a Facebook class that publishes notifications, and Mobile and Email classes that receive these notifications. We'll implement this using multicast delegates.

Delegates in C#

Step-by-Step Implementation:

  1. Define the Delegate - Create a delegate type that represents the signature of the notification methods.
  2. Define the Subscriber Classes - Create classes representing Mobile and Email services, which will receive notifications.
  3. Create and Use Multicast Delegates - Combine multiple methods into a single delegate and invoke it.

Example

using System;
namespace delegateproject
{
    public delegate void NotificationHandler(string message);
    public class Publisher
    {
        public static void PublishNotification(string message, NotificationHandler notify)
        {
            Console.WriteLine($"Facebook: Publishing notification: {message}");
            notify?.Invoke(message);
        }
    }
    
    public class Mobile
    {
        // Method to handle the notification
        public void ReceiveNotification(string message)
        {
            Console.WriteLine($"Mobile: Received notification: {message}");
        }
    }

    public class Email
    {
        // Method to handle the notification
        public void ReceiveNotification(string message)
        {
            Console.WriteLine($"Email: Received notification: {message}");
        }
    }

    public class Program
    {
        public static void Main()
        {
            Publisher Publisher = new Publisher();

            // Create instances of the subscribers
            Mobile mobile = new Mobile();
            Email email = new Email();

            // Create a multicast delegate
            NotificationHandler notify = null;

            // Add methods to the multicast delegate
            notify += mobile.ReceiveNotification;
            notify += email.ReceiveNotification;

            // Invoke the multicast delegate
            Publisher.PublishNotification("New post from your friend!", notify);
            Publisher.PublishNotification("New message received!", notify);

            // Remove a method from the multicast delegate
            notify -= mobile.ReceiveNotification;

            // Invoke the multicast delegate again
            Publisher.PublishNotification("Mobile unsubscribed, another post from your friend!", notify);
        }
    }
}

Output

Delegates in C#

The above example demonstrates how to use multicast delegates to invoke multiple methods with a single delegate. It shows how to add methods to a delegate, invoke the delegate, and remove methods from the delegate.


Prev Next