Saturday, October 24, 2015

Delegate in .Net

A delegate is a type that defines a method signature. When you create an instance of the delegate, you can associate a method to the instance of compatible signature, now you can call or invoke that method by the delegate instance.
  1. Delegates are used to pass a method as argument to other method. 
  2. A delegate instance can be assigned a method of any accessible class or struct that matches signature of delegate, method can be static or instance method.
  3. Delegate types are sealed they can not be derived from. (Sealed restricts inheritance of any class, like struct can't be inherited as they are sealed)
  4. Instance of delegate is an object so it can be assign to a property or can be pass to a method as parameter.
  5. Delegate can be multicast.
Using delegate is 4 step process 
  1. Declare delegate 
  2. Create instance / object of delegate (Create delegate pointer)
  3. Reference delegate instance to one or more methods with same signature
  4. Call delegate 

Example
namespace ClassLibrary1
{
    public class Class1
    {
        //-1-Declare delegate
        public delegate string DelSaveData(string msg);

        public DelSaveData SaveClientData()
        {
            //-2-Create delegate pointer (object)
            DelSaveData delObj = null;
           
            //-3-Point method(s) / reference to method(s)
            delObj += SaveData;
            delObj += SendMailtoClient;
            delObj += SendSMStoClient;

            return delObj;           
        }
       
        private string SaveData(string msg)
        {
            return "Data saved at : " + DateTime.Now.ToString();
        }
        private string SendMailtoClient(string msg)
        {
            return "Email sent to client at : " + DateTime.Now.ToString();
        }
        private string SendSMStoClient(string msg)
        {
            return "SMS sent to "+ msg +" at : " + DateTime.Now.ToString();
        }

    }
}

Client Code
private void button1_Click(object sender, EventArgs e)
{
   Class1 objclass1 = new Class1();
   Class1.DelSaveData objDelSaveData = objclass1.SaveClientData();
           
   //-4-Execute/call the delegate
   string s = objDelSaveData.Invoke("Client1");
}

Point to be noted in delegate multi casting : 
  1. Passed parameter(s) is available inside all assigned methods. Here "Client1" will be available to all three assigned method in msg variable.
  2. Delegate returns output returned by last called method. Here delegate invoke will return output returned by SendSMStoClient.
string s = objDelSaveData.Invoke("Client1");

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...