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 ( <parameters>)</parameters></access>
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!

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
