Delegate is type-safe object which can point to method or multiple methods (Multicasting) of application.

To define delegate we use keyword ‘Delegate’. While defining delegate we need to keep in mind that return type, arguments should be same as the return type and arguments of methods to which it is going to point to.

Example

//defining delegate
publicdelegatevoidDelegates(int x,int y);
public class clsNew
    {
//methods delegate will point to.
        public static  void Add(int x, int y)
        {
            MessageBox.Show("Sum:" + (x + y).ToString());
        }
        public static  void Mul(int x, int y)
        {
            MessageBox.Show("Product:" + (x * y).ToString());
        }
    }
         //using delegate
  private void btnAdd_Click(object sender, EventArgs e)
        {
       //creating delegate del which is pointing to Add() method of clsNew class
            Delegates del= new Delegates(clsNew.Add);    
       //actually this is pointing to add() method        
del(Convert.ToInt32(txtNum1.Text), Convert.ToInt32(txtNum2.Text));
        }


 

 

        private void btnMul_Click(object sender, EventArgs e)
        {
     //creating delegate del which is pointing to Mul() method of clsNew class
            Delegates del = new Delegates(clsNew.Mul);
//actually this is pointing to Mul() method       
del(Convert.ToInt32(txtNum1.Text), Convert.ToInt32(txtNum2.Text));
        }

 

Ability of Multicasting

Delegates can point to more than one methods but the return type of those methods should be void.

private void btnBoth_Click(object sender, EventArgs e)
        {
//delegate pointing to Add() method
            Delegates del= new Delegates(clsNew.Add);
//also pointing to Mul() method at the same time
            del+= new Delegates(clsNew.Mul);
//this will invoke both Add() and Mul() method simultaneously.
del(Convert.ToInt32(txtNum1.Text), Convert.ToInt32(txtNum2.Text));
        }

 

  1. Hi Haider M Rizvi ,

         This a Great article, it helped me alot.

    thanks for Haider M Rizvi.

Leave Comment