Conversation

Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0

Sharpen your coding skills—try JavaScript challenges on TOOLX now!

advertisement

Delegates and their Types in C# Programming

Delegates in c#


In the .NET Framework, a delegate points to one or more methods. Once you instantiate the delegate, the corresponding methods invoke. Delegates are objects that contain references to methods that must be invoked instead of containing the actual method names. Using delegates, you can call any method, which is identified only at run-time. A delegate is like having a general method name that points to various methods at different times and invokes the required method at run-time. In C#, invoking a delegate will execute the referenced method at run-time.

To associate a delegate with a particular method, the method must have the same return type and parameter type as that of the delegate.


Delegates in C#

Consider two methods, Add () and Subtract (). The method Add () takes two parameters of type integer and returns their sum as an integer value. Similarly, the method subtract () takes two parameters of type integer and returns their difference as an integer value. Since both methods have the same parameter and return types, a delegate, Calculation, can be created to be used to refer to Add () or Subtract (). However, when the delegate is called while pointing to Add(), the parameters will be added. Similarly, if the delegate is called while pointing to Subtract (), the parameters will be subtracted.

Delegates in C# have some features that distinguish them from normal methods. These features are as follows:

  • Methods can be passed as parameters to a delegate. In addition, a delegate can accept a block of code as a parameter. Such blocks are referred to as anonymous methods because they have no method name.
  • A delegate can invoke multiple methods simultaneously. This is known as multicasting.
  • A delegate can encapsulate static methods.
  • Delegates ensure type-safety as the return and parameter types of the delegate are the same as that of the referenced method. This ensures secured reliable data is passed to the invoked method.


Declaring Delegates

Delegates in C# are declared using the delegate keyword followed by the return type and the parameters of the referenced method. Declaring a delegate is quite similar to declaring a method except that there is no implementation. Thus, the declaration statement must end with a semi-colon.

declaring delegates



Instantiating Delegates

The next step after declaring the delegate is to instantiate the delegate and associate it with the required method. Here, you must create an object of the delegate. Like all other objects, an object of a delegate is Created using the new keyword. This object takes the name of the method as a parameter and this method has a signature similar to that of the delegate. The created object is used to invoke the associated method at run-time.

instantiating delegates



Using Delegates

A delegate can be declared either before creating the class (having the method to be referenced) or can be defined within the class.

There are four to implement delegates in c#, These steps are as follows:

  • Declare a delegate.
  • Create the method to be referenced by the delegate.
  • Instantiate the delegate.
  • Call the method using the object of the delegate.

An anonymous method is an inline block of code that can be passed as a delegate parameter. Using anonymous methods, you can avoid creating named methods. 



Delegate-Event Model

The delegate-event model is a programming model that enables a user to interact with a computer and computer-controlled devices using graphical user interfaces. This model consists of:

  • An event source is the console window in the case of console-based applications.
  • Listeners that receive the events from the event source.
  • A medium that gives the necessary protocol by which every event is communicated.

In this model, every listener must implement a medium for the event that it wants to listen to. Using the medium, every time the source generates an event, the event is notified to the registered listeners.

Consider a guest ringing a doorbell at the doorstep of a home. The host at home listens to the bell and responds to the ringing action by opening the door. Here, the ringing of the bell resulted in the reaction of opening the door. Similarly, in C#, an event is a generated action that triggers its reaction. For example, pressing Ctrl+Break on a console-based server window is an event that will cause the server to terminate.

This event results in storing the information in the database, which is the triggered reaction. Here, the listener is the object that invokes the required method to store the information in the database.

Delegates can be used to handle events. As parameters, they take methods that must events occur. These methods are referred to as the event handlers.



Multiple Delegates

In C#, a user can invoke multiple delegates within a single program. Depending on the delegate name or the type of parameters passed to the delegate, the appropriate delegate is invoked.


Multicast Delegate

A single delegate can encapsulate the references of multiple methods at a time. In other words, a delegate can hold several method references. Such delegates are termed as 'Multicast Delegates'. A multicast delegate maintains a list of methods (invocation list) that will be automatically called when the delegate is invoked.

Multicast delegates in C# are sub-types of the System. Multicast Delegate class. Multicast delegates are defined in the same way as simple delegates, however, the return type of multicast delegates can only be void. If any other return type is specified, a run-time exception will occur. This is because if the delegate returns a value, the return value of the last method in the invocation list of the delegate will become the return type of the delegate. This will result in inappropriate results. Hence, the return type is always void.

To add methods to the invocation list of a multicast delegate, the user can use the '+' or the '+=' assignment operator. Similarly, to remove a method from the delegate's invocation list, the user can use the '-' or the '-=' operator. When a multicast delegate is invoked, all the methods in the list are invoked sequentially in the same order in which they have been added.


System. Delegate Class

The Delegate class of the System namespace is a built-in class defined to create delegates in C#. All delegates in C# implicitly inherit from the Delegate class. This is because the delegate keyword indicates to the compiler that the defined delegate in a program is to be derived from the Delegate class. The Delegate class provides various constructors, methods, and properties to create, manipulate, and retrieve delegates defined in a program.

Constructor:

  • Delegate(object, string): Calls a method referred by the object of the class given as a parameter.
  • Delegate(type, string): Calls the static method of the class given as a parameter.

Property:

  • Method: Retcives the referenced method.
  • Target: Retrieves the object of the class in which the delegate invokes the referenced method.

Method:

  • Clone: Makes a copy of the current delegate.
  • Combine: Merges the invocation lists of the multicast delegates.
  • CreateDelegates: Declares and initializes a delegate.
  • DynamicInvoke: Callas the referenced method at run-time.


C# Delegates in c# Types of Delegates in c# Delegates in c# example use of delegates in c# delegates and events in c# advantages of delegates in c# multicast delegates in c# declaring delegates in c# instantiating delegates in c# using delegates in c# del

advertisement