Simple Example of Delegate

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
  1. static int MyMethod(int a, int b)  
  2. {  
  3.     return a + b;  
  4. }  
 4. Now give the reference of MyMethod to the delegate object of MyDelegate in the main function:
 
  
  1. MyDelegate _delegate = MyMethod;  
  2.     
  3.      int result = _delegate(5, 10);  
  4.   
  5.      Console.WriteLine(result);  
 5. Now Run it and the output will be:

 
 
Complete code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace Delegate  
  7. {  
  8.     class Program  
  9.     {  
  10.         delegate int MyDelegate(int a, int b);  
  11.   
  12.         static void Main(string[] args)  
  13.         {  
  14.             MyDelegate _delegate = MyMethod;
  15.   
  16.             int result = _delegate(5, 10);  
  17.   
  18.             Console.WriteLine(result);  
  19.         }
  20.  
  21.         #region(MyMethod)  
  22.         static int MyMethod(int a, int b)  
  23.         {  
  24.             return a + b;  
  25.         }  
  26.         #endregion  
  27.     }    
  28. }


Next Recommended Reading Delegates With A Real Time Example In C#