Combining Delegates


Being able to combine delegates is one of their most powerful features. Combining delegates means that a single delegate object can store a chain of functions, so you can invoke multiple functions from different classes with a single method call.

To combine two delegates:

  1. To combine two delegates, it's best if you have already created two other delegate objects of the same type. (For details, see the first half of "Creating and Invoking Delegates," on page 309.)

  2. Declare a variable of the same type of delegate as the delegates you are combining.

  3. Type an equal sign = .

  4. Type the name of the first delegate variable.

  5. Type a plus sign + .

  6. Type the name of the second delegate variable.

  7. Type a semicolon ; ( Figure 10.8 ).

    Figure 10.8 You can also create a delegate from the combination of two or more delegates. This enables you to call both functions with a single method call. In this example, the call to t3 actually invokes both Task1 and Task2.
     class Tasks {    public bool Task1(string desc)    {       return true;    }    public static bool Task2(string desc)    {       return true;    } } delegate bool TaskDel(string desc); public class WebForm1 : System.Web.UI.Page {    private voud Page_Load(object seder,                 System.EventArgs e)    {       Tasks tsks = new Tasks();       TaskDel t1 = new TaskDel(                       tsks.Task1);       TaskDel t2 = new TaskDel(                       Tasks.Task2);       bool result;       result = t1("Calling Task 1...");       result = t2("Calling Task 2...");  TaskDel t3 = t1 + t2;   t3("Call both delegates...");  } } 

graphics/tick.gif Tips

  • When you use the + sign, C# converts it to a call to the static function System.MulticastDelegate.Combine, which does the job of producing a delegate from the combination of two or more delegates.

  • There are really two types of delegates in the .NET framework: delegates derived from the class System.Delegate and delegates derived from the class System.MulticastDelegate . Only classes derived from System.MulticastDelegate can be combined. (C# always uses System.MulticastDelegate .)

  • The combined delegate stores a linked list of delegate objects. When you invoke a combined delegate, the framework goes through each node in the linked list and invokes the function for the particular delegate synchronously. The fact that each member in the list is invoked synchronously means that control to the program doesn't return until all the delegates have been invoked. Later in this chapter you will learn how to invoke delegates aynchronously.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net