Reviewing Delegate Members
Languages like C++ and Object Pascal support function pointers (also referred to as procedural types in Pascal) as simple types. Delegates were subclassed from the Object class and were implemented to support dynamic programming using procedure addresses to implement event handlers. Delegate is a subclass of Object in Visual Basic .NET. Table 9.1 lists and describes public members of Delegate.
Table 9.1. Delegate Members
Table 9.1 contains two strangely named methods: op_Equality and op_Inequality. Visual Basic .NET does not currently support operator overloading, but C# does. Because both languages share the same CLR and C# supports operator overloading, there has to be an intermediate form of the overloaded operator for equality and inequality.
It is an exceptionally good practice to implement overloaded operators as regular methods first and implement the overloaded operators in terms of the method. The existence of methods like op_Equality suggests that Visual Basic .NET will support operator overloading soon.
Combine and Remove are commonly used to manage multicast delegates. For the most part, other than Combine and Remove, you will probably be using delegates as procedural types and event handlers. However, for exposure to the behavior of the Delegate methods, a brief example subroutine that demonstrates some of the Delegate methods is defined in Listing 9.6.
Listing 9.6 Delegate methods example
1: Private Sub Button1_Click(ByVal sender As System.Object, _ 2: ByVal e As System.EventArgs) Handles Button1.Click 3: 4: Dim Handler As EventHandler 5: Handler = AddressOf Form1_Load 6: Handler.Invoke(sender, e) 7: Debug.WriteLine(Handler.Method().ToString()) 8: Debug.WriteLine(Handler.Target.ToString) 9: Debug.WriteLine(Handler.ToString) 10: 11: Dim Handler2 As EventHandler 12: Handler2 = AddressOf Form1_Load 13: Debug.WriteLine(EventHandler.op_Equality(Handler, Handler2)) 14: 15: End Sub
Listing 9.6 demonstrates a few Delegate members. Line 4 declares Handler as the Delegate EventHandler. Line 5 initializes Handler to the Form1_Load subroutine (which can be created by double-clicking on the form). Line 6 manually invokes the handler. In the example, line 6 causes the program to run the Form1_Load method. Line 7 prints the static Delegate method, resulting in the following line:
Void Form1_Load(System.Object, System.EventArgs)
This is the signature of the method. (The signature shown here is actually very similar to a C-style procedure declaration.) Line 8 shows the class containing the Delegate. In the example the default form, Form1, is the owner of this Delegate. Line 9 calls the ToString method. ToString is defined to display the class name , so System. EventHandler is displayed. Lines 11 and 12 declare and initialize a second Delegate to the address of Form1_Load, resulting in the op_Equality test to yield True.