C# delegates are similar to pointers to functions in C or C++.
A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
If you are not able to call any function/method directly then you can use Delegates.
Delegates are especially used for implementing events and call-back methods. All delegates are implicitly derived from the System.Delegate class.
Open Visual Studio and go to File and select New Project, then select Console Application and name it Delegate.
![]()
Define the Delegate name MyDelegate with parameters a and b:
![]()
delegate int MyDelegate(int a, int b);
3. Now Declare a Method name My method outside Main Method and in the Class.
Method name: MyMethod
Parameters: int a,int b
- static int MyMethod(int a, int b)
- {
- return a + b;
- }
4. Now give the reference of MyMethod to the delegate object of MyDelegate in the main function:
- MyDelegate _delegate = MyMethod;
-
- int result = _delegate(5, 10);
-
- Console.WriteLine(result);
5. Now Run it and the output will be:
Complete code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace Delegate
- {
- class Program
- {
- delegate int MyDelegate(int a, int b);
-
- static void Main(string[] args)
- {
- MyDelegate _delegate = MyMethod;
-
- int result = _delegate(5, 10);
-
- Console.WriteLine(result);
- }
-
- #region(MyMethod)
- static int MyMethod(int a, int b)
- {
- return a + b;
- }
- #endregion
- }
- }