Simple Delegates With Examples.
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.
- Methods don't need to match the delegate signature exactly.
- Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code that can call the referenced method, without having to know at compile time which method will be invoked.
- 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.
Example 1
Before applying the delegate:
- protected void Page_Load(object sender, EventArgs e)
- {
-
- if (!IsPostBack)
- {
- GetData("Mahesh");
- }
- }
- public void GetData(string Name)
- {
- lblName.Text = Name;
- }
Output
Mahesh
After applying the delegate:
- public delegate void MyDelegare(string var);
- protected void Page_Load(object sender, EventArgs e)
-
- {
- if (!IsPostBack)
- {
- MyDelegare objMyDelegare = new MyDelegare(GetData);
- objMyDelegare("Mahesh");
- }
- }
- public void GetData(string Name)
- {
- lblName.Text = Name;
- }
Output
Mahesh
Multicast Delegate
It is a delegate that holds the reference of more than one method.
Multicast delegates must contain only methods that return void, else there is a run-time exception.
Example 2
- public delegate void MyDelegare(string var);
- protected void Page_Load(object sender, EventArgs e)
- {
-
- if (!IsPostBack)
- {
- MyDelegare objMyDelegare = new MyDelegare(GetData);
- objMyDelegare += new MyDelegare(GetDat_one);
-
- objMyDelegare("Mahesh");
- objMyDelegare -= new MyDelegare(GetDat_one);
- lblName.Text = lblName.Text + "<br />";
-
- objMyDelegare("Mahesh");
- }
- }
-
- public void GetData(string Name){
- lblName.Text = lblName.Text + "GetDate : " + Name;
- }
-
- public void GetDat_one(string Name)
- {
- lblName.Text = lblName.Text + " GetDate_One : " + Name;
- }
Output
GetDate : Mahesh GetDate_One : Mahesh
GetDate : Mahesh