C# Delegates

Learn via video courses
Topics Covered

Overview

A delegate in C# is a reference type variable that holds the reference to a method, similar to function pointers in C/C++. It serves as an object-oriented, secure, and type-safe way to invoke methods dynamically. Delegates are especially useful for implementing events and callback mechanisms, enabling event-driven programming. Defining a delegate's method signature guarantees type safety and enables the creation of variables capable of referencing any method that conforms to the specified signature. Multicast delegates enable referencing multiple methods, executing them sequentially upon invocation. Delegates in c# play a crucial role in event handling, asynchronous programming, and facilitating functional programming paradigms.

overview of delegate in csharp

Declaration of Delegates in C#

The delegate keyword in C# is used to declare a delegate type. Once the delegate type is defined, you can create delegate instances that refer to methods with compatible signatures. Here's the syntax for declaring a delegate:

  • modifier:
    Optional access modifier, like public, private, protected, or internal.
  • return_type:
    The return type of the method the delegate can point to.
  • delegate_name:
    The name of the delegate type.
  • parameter_list:
    The list of parameters (if any) with their types and names. These must match the parameters of the methods the delegate can reference.

Instantiation and Invocation of Delegates

Once we declare a delegate type in C#, a delegate object needs to be created and associated with a specific method that has a matching signature. This process is called "instantiating the delegate". Here's the syntax for the instantiation of a delegate:

This syntax is used to create an instance of the delegate [delegate_name] and associate it with a specific method named calling_method_name that matches the delegate's signature. Once the delegate instance is created, you can use it to invoke the associated method by calling it like a regular method, passing the required parameters.

In the above example we created an instance of the MathOperation delegate named addDelegate and associated it with the Calculator.Add method using new MathOperation(Calculator.Add). Finally, we invoked the delegate addDelegate with the arguments 5 and 3, resulting in calling the Calculator.Add method, and stored the return value in the result variable. The output will show the result of the addition.

Output:

C# Delegates Multicasting

Multicasting of a delegate in C# allows you to combine multiple methods into a single delegate instance. When you invoke the delegate, all the associated methods are called in the order they were added to the delegate. This feature is useful when you want to execute multiple methods sequentially through a single delegate call.

Multicasting delegates are especially useful when you want to perform multiple operations through a single callback or event handler. They provide a convenient way to implement event notification systems, where multiple subscribers can register their methods with a single delegate, and all subscribers receive notifications when the event is raised.

Example - to illustrate delegate multicasting

Output:

In the above example

  • Delegate type MyDelegateType is declared, taking an integer parameter and returning void.
  • Two methods Method1 and Method2 are defined, matching the delegate's signature (both take an integer parameter and return void).
  • An instance of the delegate myDelegate is created and associated with the Method1.
  • Using the += operator, Method2 is added to the myDelegate, enabling delegate multicasting.
  • The delegate myDelegate is invoked with the value 42.
  • As a result of the multicasting, both Method1 and Method2 are executed in the order they were added.
  • The output displays the messages from both methods with the value 42.

Using Delegates

Delegates are fundamental in C#, enabling powerful, flexible programming techniques, event-driven and asynchronous programming, decoupling components, and easy code extensibility.

Here's an example of a delegate in C# using strings as parameters:

Example - 1:

Output:

  1. We declare a delegate type named StringOperation that takes two strings as parameters and returns a string.
  2. The StringConcatenator class contains two static methods ConcatenateStrings and JoinStrings, which perform different operations on strings.
  3. In the Main method, we create an instance of the StringOperation delegate named concatenateDelegate and associate it with the StringConcatenator.ConcatenateStrings method using new StringOperation(StringConcatenator.ConcatenateStrings).
  4. We then invoke the delegate concatenateDelegate with the arguments "Hello" and "World", resulting in calling the StringConcatenator.ConcatenateStrings method, and store the return value in result1.
  5. The value of result1 is printed to the console, displaying the concatenated string.
  6. Next, we change the delegate reference concatenateDelegate to point to the StringConcatenator.JoinStrings method using new StringOperation(StringConcatenator.JoinStrings).
  7. We then invoke the delegate concatenateDelegate with the arguments "Hello" and "World", resulting in calling the StringConcatenator.JoinStrings method, and storing the return value in result2.
  8. The value of result2 is printed to the console, displaying the joined string with a separator.

Let's explore an example of delegates in C# to better understand how they work.

Example - 2:

Output:

FAQs

Q. What are Delegate in c#?

A. Delegates in c# are reference-type variables that hold references to methods with matching signatures. They provide a way to treat methods as objects, allowing for dynamic method invocation, callback mechanisms, and event handling.

Q. How do Delegates work in C#?

A. Delegates work by creating a type-safe function pointer that points to a method. They can be associated with methods having the same signature and can be invoked, allowing the methods to be called through the delegate.

Q. What is the purpose of Delegates in C#?

A. Delegates serve various purposes, including implementing event handling, enabling callback mechanisms, supporting asynchronous programming, and allowing multicasting of methods. They promote decoupling and flexibility in code design.

Q. How are Delegates declared and used in C#?

A. Delegates are declared using the delegate keyword, specifying the return type and parameter list. Instances of delegates can then be created, associated with methods, and invoked using the += operator for multicasting.

Conclusion

  • A delegate in C# is a reference type variable that holds the reference to a method, similar to function pointers in C/C++.
  • Multicasting of a delegate in C# allows you to combine multiple methods into a single delegate instance.
  • Multicasting delegates are especially useful when you want to perform multiple operations through a single callback or event handler.
  • Delegates work by creating a type-safe function pointer that points to a method.
  • Delegates are declared using the delegate keyword, specifying the return type and parameter list.
  • Instances of delegates can then be created, associated with methods, and invoked using the += operator for multicasting.