Delegates in C#: Complete tutorial

by | Dec 3, 2023 | C# OOP | 0 comments

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-

In this example:

  • CallbackDelegate is a delegate type with a signature that matches a method accepting a string parameter.
  • CallbackExample class has a method called PerformOperationWithCallback 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 of CallbackExample is created, a callback delegate is instantiated and set to point to the DisplayMessage method, and then the PerformOperationWithCallback 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:

  1. 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. Define an Event: Next, you define an event using the delegate. This event will be responsible for notifying subscribers when the event occurs.
  1. 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. Attach Event Handlers: Instances of the subscribing class can then attach their methods to the event.
  1. Trigger the Event: Finally, when the event occurs in the publisher class, all subscribed event handlers will be notified.

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:

  1. Define a Singlecast Delegate: Define a delegate with a specific signature. This delegate can hold a reference to a single method.
  1. 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. Invoke the Singlecast Delegate: When you invoke the singlecast delegate, the assigned method will be called.

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:

  1. 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. Create a Multicast Delegate: Instantiate a delegate object, which can be assigned multiple methods.
  1. Assign Methods to the Multicast Delegate: Assign methods to the delegate using the += operator.
  1. Invoke the Multicast Delegate: When you invoke the multicast delegate, all the methods it references will be called in the order they were added.

Both Method1 and Method2 will be called with the “Hello” message.

  1. Remove Methods from the Multicast Delegate: You can also use the = operator to remove a method from the multicast delegate.

Now, the multicastDelegate will only invoke Method2 when invoked.

Here’s a simple example:

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:

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

Please leave a comment if you think something can be improved.

0 Comments

Related Posts

Inheritance in C# oops complete guide

Inheritance Table of content: Topics1Why i wrote this article2Inheritance - complete guide3All possible scenarios based/ tricky in/out type of Interview questions Why i wrote this article? When I was preparing c#/oops, the main challenge was information was scattered...

Index:C# OOP

Inheritance in C# oops complete guide

Inheritance Table of content: Topics1Why i wrote this article2Inheritance - complete guide3All possible scenarios based/ tricky in/out type of Interview questions Why i wrote this article? When I was preparing c#/oops, the main challenge was information was scattered...

Learn C# oops Polymorphism

Polymorphism Simplifying Polymorphism in C# with Examples Polymorphism is a fundamental concept in object-oriented programming (OOP), and it can be understood more easily by breaking it down into its key components. What is Polymorphism? At its core, polymorphism...