C# Delegates

03 Jul 2024
Beginner
224 Views
5 min read
Learn via Video Course & by Doing Hands-on Labs

Free C# Course Online

C# Delegates- An Overview

Delegates in C# play a pivotal role in enabling event handling, callback mechanisms, and creating extensible and flexible software. This article delves into the fundamental concepts of delegates, their usage, and how they empower developers to build efficient and adaptable applications in the C# programming language.

What is Delegates in C# ?

In C#, delegates are type-safe function pointers that allow methods to be passed as parameters or assigned to variables. They enable defining and invoking methods dynamically at runtime, enhancing the flexibility and extensibility of code. Delegates are essential for implementing events and callbacks in C# applications.

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#.

Multicasting of a Delegate

In C#, multicasting of a delegate allows combining multiple methods into a single delegate instance. Use the += operator to add methods and -= to remove. When the delegate is invoked, all attached methods are called in the order they were added.

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.

What is the anonymous delegate in C#

An anonymous delegate in C# is an inline, unnamed method used to define a code block without explicitly declaring a separate method. It is often employed for event handling or passing a code block as a parameter to a method.

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
Conclusion

In conclusion, delegates in C# provide a powerful mechanism for implementing callbacks and event handling in a type-safe manner. They enhance the flexibility and extensibility of C# programs, enabling efficient communication between objects. Understanding delegates is crucial for developers seeking to create robust and responsive applications in the C# programming language.

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 06SAT, 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 8th time in a row (2016-2023). 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