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.
- Delegates are used to pass a method as argument to other method.
- 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.
- 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)
- Instance of delegate is an object so it can be assign to a property or can be pass to a method as parameter.
- Delegate can be multicast.
Using delegate is 4 step process
- Declare delegate
- Create instance / object of delegate (Create delegate pointer)
- Reference delegate instance to one or more methods with same signature
- 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;
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();
}
}
}
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 :
- Passed parameter(s) is available inside all assigned methods. Here "Client1" will be available to all three assigned method in msg variable.
- 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