Simple Program of Delegates in C#


C# Contains two kinds of objects, those that create changes and those that respond to that changes. A Delegates acts as a tunnel between these two kinds of objects that move information from one side to another.

A C# delegates are class methods and can be either static or instance class methods. A delegate can keep track of its own state by maintain information in the object to which it belongs.

We can create delegates by using “Delegate” Keyword as shown below:

  1. Public delegate int MyDelegate (int x);  
A Delegate is not a method or a function it’s a kind of definition of function pointer. Therefore you cannot directly use a Delegate you need a function associated with it.

For creating a delegate use these two steps: 
  1. You need to have a delegate in a class that acts the conduit pointer for use by the delegate source.

  2. You need a live method that acts as the concrete functionality that is called when delegate is invoked.

Let’s Create one simple Program of delegates in Console:

Program of delegates in Console

Here is the Code of Delegates:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  6. namespace Delegates_demo  
  7. {  
  8.     public delegate int Mydelegate(int x,int y);  
  9.     class sample  
  10.     {  
  11.         public static int rectangle(int a, int b)  
  12.         {  
  14.             return a * b;  
  15.         }  
  17.     }  
  19.     class Program  
  20.     {  
  21.         static void Main(string[] args)  
  22.         {  
  23.             Console.WriteLine("My simple Delegate Program");  
  24.             Mydelegate mdl = new Mydelegate(sample.rectangle);  
  25.             Console.WriteLine("The Area of rectangle is {0}", mdl(4, 5));  
  26.             Console.ReadKey();  
  27.         }  
  28.     }  
  29. }  
Output of Delegates:

Output of Delegates

Hope you like this Article. Have a good day! Thank you for Reading!