Learn Delegates c#
In C#, a delegate is a type that represents references to methods with a particular parameter list and return type.
Delegates provide a way to encapsulate a method, and they are often used for defining callback methods and implementing event handling.
Encapsulation of a Method
- It allows you to treat methods as entities that can be assigned to variables, passed as parameters to other methods, and returned from methods.
- In simpler terms, you can create a delegate variable, and then assign a method to that variable. This allows you to call the method using the delegate variable.
Callback Methods:
- Delegates are commonly used for implementing callback methods.
- A callback is a method that is passed as an argument to another method and is expected to be called at some later time.
- Delegates provide a way to define and pass around these callback methods in a type-safe manner.
How Call back works?
In C#, a delegate is a type that represents references to methods with a specific signature. Delegates are often used for implementing callbacks, where a method (the callback) is passed as an argument to another method, and the receiving method is expected to call the provided callback at some later time.
Example-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
using System; // Define a delegate with a specific signature public delegate void CallbackDelegate(string message); public class CallbackExample { // Method that takes a callback delegate as an argument public void PerformOperationWithCallback(string input, CallbackDelegate callback) { // Perform some operation with the input // Invoke the callback method, passing a message callback("Operation completed successfully!"); // Perform other tasks } } public class Program { // Callback method that matches the signature of the delegate public static void DisplayMessage(string message) { Console.WriteLine($"Callback message: {message}"); } public static void Main() { // Create an instance of the CallbackExample class CallbackExample example = new CallbackExample(); // Create an instance of the delegate, pointing to the DisplayMessage method CallbackDelegate callbackDelegate = new CallbackDelegate(DisplayMessage); // Call the method with the callback delegate as an argument example.PerformOperationWithCallback("Some input", callbackDelegate); } } |
In this example:
CallbackDelegate
is a delegate type with a signature that matches a method accepting astring
parameter.CallbackExample
class has a method calledPerformOperationWithCallback
that takes a string input and a callback delegate as arguments. It performs some operation with the input and then invokes the callback, passing a message.DisplayMessage
is a method with the same signature as the delegate. It serves as the callback method in this example.- In the
Main
method, an instance ofCallbackExample
is created, a callback delegate is instantiated and set to point to theDisplayMessage
method, and then thePerformOperationWithCallback
method is called with the callback delegate as an argument.
When the operation in PerformOperationWithCallback
is completed, it invokes the callback, and the DisplayMessage
method is called, displaying the message provided in the callback. This demonstrates the use of a callback in C# with delegates.
Benefit as in async operations?
the callback method will be called when the operation in the PerformOperationWithCallback
method is completed, even if the Main
method takes 5 seconds to execute. The concept of callbacks is often used for asynchronous or long-running operations.
Event Handling
- In C#, an event is a mechanism that enables a class or object to provide notifications to other classes or objects when something of interest happens. Event handling in C# is a way to respond to these notifications or events.
- In simple terms, event handling is like setting up a system where one part of your program (the publisher) can notify other parts (the subscribers) when a specific event occurs. The subscribers can then respond to the event by executing some predefined code.
Here’s a brief overview of how event handling works in C# using delegates:
- Define a Delegate: First, you define a delegate that will act as the contract for the event handler methods. The delegate defines the method signature that the event handlers must adhere to.
1 2 3 4 |
public delegate void MyEventHandler(object sender, EventArgs e); |
- Define an Event: Next, you define an event using the delegate. This event will be responsible for notifying subscribers when the event occurs.
1 2 3 4 5 6 7 |
public class MyClass { public event MyEventHandler MyEvent; } |
- Subscribe to the Event: Other parts of your program (classes or methods) can subscribe to the event by providing methods that match the delegate’s signature.
1 2 3 4 5 6 7 8 9 10 |
public class Subscriber { public void HandleEvent(object sender, EventArgs e) { // Code to handle the event } } |
- Attach Event Handlers: Instances of the subscribing class can then attach their methods to the event.
1 2 3 4 5 6 |
MyClass myObject = new MyClass(); Subscriber subscriber = new Subscriber(); myObject.MyEvent += subscriber.HandleEvent; |
- Trigger the Event: Finally, when the event occurs in the publisher class, all subscribed event handlers will be notified.
1 2 3 4 5 6 7 |
if (MyEvent != null) { MyEvent(this, EventArgs.Empty); } |
What is Single cast Delegate:
A singlecast delegate in C# is a delegate that can hold a reference to a single method. It represents a one-to-one relationship between the delegate and the method it references. Here’s a breakdown:
- Define a Singlecast Delegate: Define a delegate with a specific signature. This delegate can hold a reference to a single method.
1 2 3 4 |
public delegate void SinglecastDelegate(string message); |
- Instantiate and Assign a Method: Instantiate the delegate and assign a method to it. This method will be the one invoked when the delegate is called.
1 2 3 4 |
SinglecastDelegate singlecastDelegate = Method1; |
- Invoke the Singlecast Delegate: When you invoke the singlecast delegate, the assigned method will be called.
1 2 3 4 |
singlecastDelegate("Hello"); |
This will call Method1
with the “Hello” message.
What is multicast delegate
In C#, a multicast delegate is a type of delegate that can hold references to multiple methods, and it can invoke all the methods it references in the order in which they were added. This is in contrast to a singlecast delegate, which can hold a reference to only one method.
Here’s a brief explanation of multicast delegates:
- Delegate Definition: Define a delegate with a specific signature. This delegate will act as a template for methods that can be assigned to it.
1 2 3 4 |
public delegate void MyDelegate(string message); |
- Create a Multicast Delegate: Instantiate a delegate object, which can be assigned multiple methods.
1 2 3 4 |
MyDelegate multicastDelegate = null; |
- Assign Methods to the Multicast Delegate: Assign methods to the delegate using the
+=
operator.
1 2 3 4 |
multicastDelegate += Method1; multicastDelegate += Method2; |
- Invoke the Multicast Delegate: When you invoke the multicast delegate, all the methods it references will be called in the order they were added.
1 2 3 4 |
multicastDelegate("Hello"); |
Both Method1
and Method2
will be called with the “Hello” message.
- Remove Methods from the Multicast Delegate: You can also use the
=
operator to remove a method from the multicast delegate.
1 2 3 |
multicastDelegate -= Method1; |
Now, the multicastDelegate
will only invoke Method2
when invoked.
Here’s a simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using System; public delegate void MyDelegate(string message); public class MulticastDelegateExample { public static void Method1(string message) { Console.WriteLine($"Method1: {message}"); } public static void Method2(string message) { Console.WriteLine($"Method2: {message}"); } public static void Main() { MyDelegate multicastDelegate = null; multicastDelegate += Method1; multicastDelegate += Method2; // Invoke all methods in the multicast delegate multicastDelegate?.Invoke("Hello"); // Output: // Method1: Hello // Method2: Hello } } |
In this example, the multicastDelegate
holds references to both Method1
and Method2
, and invoking the delegate calls both methods in the order they were added. Multicast delegates are commonly used in scenarios where you want to notify multiple listeners about an event or perform multiple actions in response to a single event.
Difference ?
In terms of syntax and definition, both singlecast and multicast delegates are declared in the same way. The key difference lies in how you use the +=
and -=
operators.
- For a singlecast delegate, you use
=
to assign a single method to the delegate:SinglecastDelegate singlecastDelegate = Method1;
- For a multicast delegate, you use
+=
to add methods and=
to remove methods:
1 |
MulticastDelegate multicastDelegate = null; multicastDelegate += Method1; multicastDelegate += Method2; |
So, in terms of syntax, the declaration and invocation are similar, but the use of +=
and -=
is what distinguishes a multicast delegate from a singlecast delegate. A singlecast delegate can be reassigned with a new method using =
(replacing the existing method), while a multicast delegate allows you to add multiple methods using +=
and remove them using -=
.
1 2 3 4 5 6 7 8 9 |
// Singlecast delegate (reassignment) singlecastDelegate = AnotherMethod; // Multicast delegate (addition and removal) multicastDelegate += AnotherMethod; multicastDelegate -= Method1; |
Please leave a comment if you think something can be improved.
0 Comments