Concept Of A Delegate In C#

Basic delegate

An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.

A delegate is a form of type-safe function used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on.

or

Shifting of work from one's control to another.

  • delegate is keyword to make delegates in our program.
  • Delegate is also work as class which has a base class Delegate (abstract class).
  • Delegates are used to pass methods as arguments to other methods.
In event handling its too difficult to have a person for every event differently,

Delegate In C#
Delegates have the following properties
  1. Delegates are similar to C++ function pointers, but are type safe.
  2. Delegates allow methods to be passed as parameters.
  3. Delegates can be used to define callback methods.
  4. Delegates can be chained together; for example, multiple methods can be called on a single event.

Syntax

  1. publicdelegate<return type>DelegateName();  
Program
  1. using System;  
  2. namespace Deligate {  
  3.     publicdelegateintMyfirstDeligate(int i, int j);  
  4.     publicdelegatevoidMySecondDeligate();  
  5.     classProgram {  
  6.         publicint Add(int i, int j) {  
  7.             return i + j;  
  8.         }  
  9.         publicint Sub(int i, int j) {  
  10.             return i - j;  
  11.         }  
  12.         publicvoid Show() {  
  13.             Console.WriteLine("MCN SOLUTION PVT LTD.");  
  14.         }  
  15.         publicvoid Display() {  
  16.             Console.WriteLine("Hi");  
  17.         }  
  18.         staticvoid Main(string[] args) {  
  19.             Program p = newProgram();  
  20.             MyfirstDeligate m = newMyfirstDeligate(p.Add);  
  21.             int result = m(9, 5);  
  22.             m = newMyfirstDeligate(p.Sub);  
  23.             int result1 = m(50, 10);  
  24.             Console.WriteLine(result + " " + result1);  
  25.             MySecondDeligate m2 = newMySecondDeligate(p.Show);  
  26.             MySecondDeligate m3 = newMySecondDeligate(p.Display);  
  27.             m2 = m2 + m3;  
  28.             m3 = m2 - m3;  
  29.             m2();  
  30.             m3();  
  31.             Console.Read();  
  32.         }  
  33.     }  
  34. }  

Output

Delegate In C#