11
OctDelegates in c sharp | Types of Delegates
In-Depth Understanding of C# Delegates
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.
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#?
Q2. What is the real-time use of delegates in C#?
Q3. Where should delegates be declared C#?
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.