Delegates

We can think delegate type as a single method interface , and a delegate instance as an object implementing that interface.

As an example, consider your will, “pay the bills, make a donation to the charity,leave the rest of my estate to my cat” for instance you write it before your death and leave it in an appropiately safe place . After your death, your attorny will act on those instructions.”

A delegate in c# acts like your will in real world- it allows you to specify a sequence of actions to be executed at the appropriate time.

A Recipe for Simple Delegates

In order for a delegate to do anything , four things need to happen

  1. The delegate Type needs to be declared
  2. The code to be executed must be contained in a method
  3. The delegate instance must be created
  4. The delegate instane must be invoked

Example

class Program
 {
   delegate void StringProessor(string input);
   static void Main(string[] args)
   {
     Person jon = new Person("jon");
     Person tom = new Person("Tom");
 
     StringProessor jonsVoice, tomsVoie, background;
 
     jonsVoice = new StringProessor(jon.Say);
     tomsVoie= new StringProessor(tom.Say);
     background = new StringProessor(Background.Note);
 
     jonsVoice("HelloSon");
     tomsVoie.Invoke("Hello, Dady!");
     background("An Airplae files past");
   }
 }
 
 class Person
 {
   string name;
 
   public Person(string name)
   {
     this.name = name;
   }
 
   public void Say(string message)
   {
     Console.WriteLine("{0} says: {1}", name , message);
   }
 }
 
 class Background
 {
   public static void Note(string note)
   {
     Console.WriteLine("{0}",note);
   }
 }
Advertisements