C# Delegates
C# delegates play an important role when we want to handle any event or callback in our code or we can say that a function having more than one parameter of a different data type but we want to pass a function itself rather than a parameter. In this case, delegates come in the picture because it acts like a pointer to a function, since it is a reference data type therefore it holds the reference of the method. Delegates are the part of System.Delegates class in C#. They are similar to a function pointer in C and C++ programming.
Syntax
Lets have a look at the syntax of declaring delegates in C #
<access modifier> delegate < return type > < delegate_name > ( <parameters>)
Explanation: In the above syntax access modifier has to be declared before declaring delegates, as it can be public, private, or protected. Now for declaring delegate we have to use the keyword delegate followed by the function return type. For Example,
public delegate void Show ( char ch );
The show delegate used above is used to point at any method that has same parameter and return type associated with function Show () .
Examples to Implement C# Delegates
Below are the examples mentionedL
Example #1
Code to demonstrate the working of single cast delegates :
Code:
using System; class Singlecast_Delegates { public delegate void Delete_func() ; public class SD { public static void text_display() { Console.WriteLine ( " Hey hello ! , How are you " ) ; } public static void text_show() { Console.WriteLine ( " Hi ! How is everything ? " ) ; } public void print() { Console.WriteLine ( " Print " ) ; } } static void Main(string[] args) { Delete_func del_var1 = SD.text_show ; Delete_func del_var2 = new Delete_func ( SD.text_display ) ; SD obj = new SD() ; Delete_func del_var3 = obj.print ; del_var1() ; del_var2() ; del_var3() ; Console.ReadLine () ; } }
Output :
Explanation: In the above code, you can see we have assigned static method text_show() of class SD to delegate Delete_func() then we have assigned static method text_display() of class SD to delegate Delete_func() using the new operator. In addition, we can use both the ways to assign the delegate function. Therefore, at first, we have created an instance of class SD and assigned the method print() to the delegate which means delegate with class. In the end, we created the object for SD class so that we can call the function one by one which we have created in our code.
Example #2
Code to demonstrate the working of double cast delegates :
Code:
using System ; namespace Educba { // Here we are declaring the class with name " Edu " class Edu { // In this class we will declare the delegates // Here the return type and parameter type must be same as the return and parameter type // of the 2 methods // "number_addition" and "number_substraction" are 2 given delegate names by user public delegate void number_addition ( int x , int y ) ; public delegate void number_substraction ( int x , int y ) ; // here we are declaring the "total" method public void total ( int x , int y ) { Console.WriteLine( " (50 + 10) = {0} " , x + y ) ; } // here we are declaring the "substraction" method public void substraction ( int x , int y ) { Console.WriteLine( " ( 95 - 30 ) = {0} ", x - y ) ; } // Main Method declaration public static void Main(String []args) { // creating an object " obj " for "Edu" Edu obj = new Edu() ; number_addition delegate1 = new number_addition ( obj.total ) ; number_substraction delegate2 = new number_substraction( obj.substraction ) ; // creating an object of the delegate class named as " delegate1 " // for method "total" and "delegate2" for method "substraction" & // pass the parameter of the 2 methods by class object "obj" // by instantiating the delegates // passing the below values to the methods by declared delegate object delegate1( 50 , 10) ; delegate2( 95 , 30); } } }
Output:
Exaplanation: In the above code, you can see we are using double-casting delegates which is different than the single cast delegates. We have declared the class with name Edu and this class we have declared two delegates where one is for the addition of two integers while the other one is for the subtraction of 2 given integer at a time. After that, we have declared a method total for storing the results of addition delegates. In the same way, we have declared one more method for storing the result of subtraction delegates. In the main class, we are creating the object of Edu class so that we can call the delegates to function for performing addition and subtraction on any two given integer numbers. We will pass the value and get the results.
Example #3
Code to demonstrate the working of anonymous delegates:
Code:
using System; // declaring delegate method Demo of void type public delegate void Demo() ; // creating a class for declaring a static method inside this class. public class First_Program { static int Main() { Demo Display = delegate() { // displaying the output on the user screen Console.WriteLine ( " Here is the Anonymous delegate method " ) ; }; // Here we are calling the display function. Display() ; return 0 ; } }
Output :
Conclusion
whenever a coder needs to pass a method as an argument of other methods then we use delegates or we can say that delegates are a class through which we can encapsulate a function signature. It is more like giving a name to a method parameter in C#.
The above is the detailed content of C# Delegates. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.
