Navratri Sale: Get Upto 30% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Delegates in c sharp |  Types of Delegates

Delegates in c sharp | Types of Delegates

07 Oct 2024
Beginner
308 Views
12 min read
Learn via Video Course & by Doing Hands-on Labs

Free C# Course Online

In-Depth Understanding of C# Delegates

C# Delegates are essential for developers aiming to manage method references dynamically and efficiently. Imagine having the ability to pass methods as parameters, enabling event handling, callbacks, and dynamic method invocation, all while ensuring type safety. Delegates in C# offer a flexible way to work with methods, providing built-in mechanisms for invoking, combining, and managing method references without additional complexity.
In this C# tutorial, I’ll explain the different types of Delegates, how they simplify method management by enabling versatile programming patterns, and why mastering them is key to writing flexible, scalable C# applications.

What is Delegates in C#?

  • Delegates in C# are unique types that allow you to reference methods, acting like function pointers in other programming languages.
  • They enable you to pass methods as parameters, allowing for more flexible and reusable code.
  • Delegates can use any method that matches their signature, including methods with varying return types and parameters.
  • C# provides various types of delegates, such as Func, Action, and Predicate, each serving different purposes.
For example, Action is ideal for referencing methods that return void, while Func is used when methods return values. Delegates make it easier to implement callbacks, event handling, and flexible method invocations, leading to more modular and maintainable code.

Important Points About Delegates in C#

  • Delegates are type-safe function pointers.
  • They define the signature of the methods they can reference.
  • Delegates can point to static or instance methods.
  • They allow methods to be passed as parameters.
  • Delegates enable event handling and callback mechanisms.
  • Multicast delegates can point to multiple methods.
  • Delegates are widely used in event-driven programming in C#.

What are the benefits of delegates in C#?

Delegates in C# offer several advantages:

  • Function Pointers: Delegates allow functions to be treated as objects, enabling dynamic method invocation.
  • Callback Mechanism: Delegates enable callbacks, allowing one method to call another method asynchronously.
  • Event Handling: Delegates are fundamental for implementing event handling in C# applications.
  • Multicast: Multiple methods can be combined into a single delegate, simplifying the invocation of multiple methods.
  • Decoupling: Delegates decouple sender and receiver objects, enhancing flexibility and maintainability in code.
  • Dynamic Method Binding: Delegates enable dynamic binding of methods at runtime, enhancing flexibility in program design

Declaration of Delegates

  • The delegate keyword can be used to declare a delegate type.
  • The methods whose return type and argument list match the delegate declaration will be referred to and called by the delegate instance once it has been defined.

Syntax

[modifier] delegate [return_type] [delegate_name] ([parameter_list]);

Example

// "public" is the modifier
// "int" is return type
// "DotnetTricks" is delegate name
// "(int D, int N, int T)" are the parameters
public delegate int DotnetTricks(int D, int N, int T);

Explanation

  • This code snippet declares a public delegate named DotnetTricks in C#.
  • It defines a delegate that takes three parameters of type int (D, N, T) and returns an int value.
  • Delegates like this allow the encapsulation of methods with matching signatures, enabling dynamic method invocation and function pointers in C#.

Instantiation & Invocation of Delegates

  • A delegate object is produced following the declaration of a delegate with the use of a new keyword.
  • A delegate is sent to a method at instantiation, passing back any method calls made to it.
  • The caller passes the parameters to the delegate, who then passes them to the method.
  • The delegate then returns any return values from the method to the caller. We refer to this as calling upon the delegate.

Syntax

[delegate_name] [instance_name] = new [delegate_name](calling_method_name);

Example

DotNetTricks DNT = new DotNetTricks (Scholar);
 // here,
 // "DontNetTricks" is delegate name. 
 // "DNT" is instance_name
 // "Scholar" is the calling method.

Explanation

  • This code creates an instance of the DotNetTricks delegate named DNT and associates it with the method Scholar.
  • Now, invoking DNT will execute the functionality defined in the Scholar method.
  • Delegates like this provide a way to achieve callback mechanisms and dynamic method invocation in C#.

Example

using System;

public class Program
{
    // Step 1: Declare the delegate
    public delegate void SimpleDelegate(string message);

    // Step 2: Create a method matching the delegate signature
    public static void Scholar(string message)
    {
        Console.WriteLine("Message from Scholar method: " + message);
    }

    public static void Main()
    {
        // Step 3: Instantiate the delegate and pass the method
        SimpleDelegate DNT = new SimpleDelegate(Scholar);

        // Step 4: Invoke the delegate (this will call the Scholar method)
        DNT("Hello from Delegate!");

        // Output: "Message from Scholar method: Hello from Delegate!"
    }
}

Output

Message from Scholar method: Hello from Delegate!

Explanation

  • This C# program demonstrates the use of a delegate.
  • A delegate named SimpleDelegate is defined, matching the method signature of the Scholar.
  • The delegate is instantiated and used to call the Scholar method, passing a string message to be printed.

Multicasting of a Delegate

  • Multicasting of a delegate in C# allows multiple methods to be combined into a single delegate instance.
  • When invoked, all the methods attached to the delegate are executed sequentially, following a First In, First Out (FIFO) order.
  • You can add methods using the += operator and remove them using the -= operator, enabling flexible method chaining and execution.
  • Multicasting is useful for triggering multiple methods with a single delegate call.

Properties

  • Combining delegate calls results in the calling of an entire array of methods.
  • The sequence in which all methods are called is First in First Out (FIFO).
  • The operators "+" or "+=" are used to append methods to delegates.
  • '–' or '-=' The methods are eliminated from the list of delegates using the operator.
using System;

public class Program
{
    // Step 1: Declare the delegate
    public delegate void NotifyDelegate();

    // Step 2: Create methods that match the delegate signature
    public static void Method1()
    {
        Console.WriteLine("Method1 is called.");
    }

    public static void Method2()
    {
        Console.WriteLine("Method2 is called.");
    }

    public static void Main()
    {
        // Step 3: Instantiate the delegate and add methods using +=
        NotifyDelegate notify = Method1;
        notify += Method2;

        // Step 4: Invoke the delegate (both methods will be called)
        notify();

        // Output:
        // Method1 is called.
        // Method2 is called.
    }
}

Output

Method1 is called.
Method2 is called.

Explanation

  • This code demonstrates the multicasting of a delegate in C#, where two methods (Method1 and Method2) are added to a delegate using the += operator.
  • When the delegate notification is invoked, both methods are executed in the order they were added.

What is the anonymous delegate in C#

  • Anonymous delegates in C# are methods without a name, defined inline using the delegate keyword.
  • They allow you to create and pass methods on the fly, enabling more concise and flexible code.
  • Anonymous delegates can be used wherever a regular delegate is expected, matching the required signature for parameters and return types.
  • They are often used for small, one-time-use methods without the need to define a separate function.

Let's explore this simple example.

Example

using System;

public delegate void Test();

public class Program
{
static int Main()
{
Test Display = delegate()
{
Console.WriteLine("Anonymous Delegate method");
};

Display();
return 0;
}
}

Explanation

  • The code defines an anonymous delegate using the delegate keyword and assigns it to a delegate instance named Display.
  • When the Display delegate is invoked, it prints the specified message to the console.

Output

Anonymous Delegate method
Summary

Delegates in C# are type-safe method references that allow methods to be passed as parameters, supporting event handling, callbacks, and dynamic method invocation. They can reference methods with matching signatures and are used for creating flexible, modular, and extensible code. Common types of delegates include Func, Action, and Predicate, and they support multicasting, enabling the invocation of multiple methods. To master more C# concepts, enroll in Scholarhat's C# Programming Course.

FAQs

Q1. What is the main use of delegates in C#?

The main use of delegates in C# is to allow methods to be passed as parameters, enabling event handling, callbacks, and dynamic method invocation. They provide a type-safe mechanism for referencing and invoking methods, making code more flexible and modular.

Q2. What is the real-time use of delegates in C#?

In real-time applications, delegates in C# are commonly used for implementing event handling (e.g., UI events like button clicks), callbacks in asynchronous programming, and multicasting to execute multiple methods with a single call. They help decouple components, enhancing flexibility and maintainability.

Q3. Where should delegates be declared C#?

Delegates in C# are typically declared at the namespace or class level, outside of methods, to make them accessible throughout the class or across multiple classes. This allows the delegate to be used for event handling, callbacks, or passing methods as parameters.

Take our Csharp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Full-Stack .NET Developer Certification TrainingOct 13SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this