Delegates
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:
- 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: - You need to have a delegate in a class that acts the conduit pointer for use by the delegate source.
- 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:
Here is the Code of Delegates:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace Delegates_demo
- {
- public delegate int Mydelegate(int x,int y);
- class sample
- {
- public static int rectangle(int a, int b)
- {
-
- return a * b;
- }
-
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("My simple Delegate Program");
- Mydelegate mdl = new Mydelegate(sample.rectangle);
- Console.WriteLine("The Area of rectangle is {0}", mdl(4, 5));
- Console.ReadKey();
- }
- }
- }
Output of Delegates:
Hope you like this Article. Have a good day! Thank you for Reading!