Introduction
A delegate is an object that points to a method; alternatively, it may be thought of as a variable of the reference type that stores references to the methods. Similar to the function pointer in C/C++, delegates are used in C#. It offers a mechanism to specify which method should be invoked in the case that an event is triggered.
For instance, the application would invoke a particular procedure whenever you click on a button on a Windows Form application. Put simply, it's a type that holds references to methods that have a specific argument list and return type, and when a program needs to use a method, it invokes the method for execution.
Crucial information regarding delegates
Offers a useful means of summarizing the techniques.
The library class in the System namespace is a delegate.
Any method's type-safe pointer is this.
Implementing call-back functions and events is the primary usage of delegates.
Since several methods can be called on a single event, delegates can be chained together.
The class of the object it references is irrelevant to it.
Additionally, delegates can be invoked using "anonymous methods."
In certain scenarios, delegate types are compiled using Lambda expressions (C# 3.0) and Anonymous Methods (C# 2.0). These characteristics collectively are sometimes referred to as anonymous functions.
Declaring of Delegates
The delegate keyword can be used to declare a delegate type. The methods whose return type and argument list match the delegate declaration will be referred to and called by the delegate instance once it has been declared.
Syntax
[modifier] delegate [returnType] [delegateName] ([parameterList]);
- Modifier: This is an optional modifier that is necessary to define the delegate's access.
- Delegate: This term is used to specify what a delegate is.
- returnType: This refers to the kind of value that the delegate's methods will return. It might be null and void. The return type of a method must match that of the delegate.
- delegateName: This is the name or identifier for the delegate that the user has defined.
- parameterList: This lists the parameters that, when called through the delegate, the method needs.
As an illustration
// "public" is the modifier
// "int" is return type
// "Addition" is delegate name
// "(int a, int b)" are the parameters
public delegate int Addition(int a, int b);
Note. A delegate will only invoke a method whose signature and return type match. It doesn't matter if a method is an instance method linked to an object or a static method associated with a class.



Join the conversation! Your thoughts help the community grow.