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,
Delegates have the following properties
- Delegates are similar to C++ function pointers, but are type safe.
- Delegates allow methods to be passed as parameters.
- Delegates can be used to define callback methods.
- Delegates can be chained together; for example, multiple methods can be called on a single event.
Syntax
- publicdelegate<return type>DelegateName();
Program
- using System;
- namespace Deligate {
- publicdelegateintMyfirstDeligate(int i, int j);
- publicdelegatevoidMySecondDeligate();
- classProgram {
- publicint Add(int i, int j) {
- return i + j;
- }
- publicint Sub(int i, int j) {
- return i - j;
- }
- publicvoid Show() {
- Console.WriteLine("MCN SOLUTION PVT LTD.");
- }
- publicvoid Display() {
- Console.WriteLine("Hi");
- }
- staticvoid Main(string[] args) {
- Program p = newProgram();
- MyfirstDeligate m = newMyfirstDeligate(p.Add);
- int result = m(9, 5);
- m = newMyfirstDeligate(p.Sub);
- int result1 = m(50, 10);
- Console.WriteLine(result + " " + result1);
- MySecondDeligate m2 = newMySecondDeligate(p.Show);
- MySecondDeligate m3 = newMySecondDeligate(p.Display);
- m2 = m2 + m3;
- m3 = m2 - m3;
- m2();
- m3();
- Console.Read();
- }
- }
- }
Output