5.8. Generic Methods and Delegates

Delegates leverage references to methods. And, generic methods are no exception to that rule. They can participate in the definition of a delegate like any other non-generic method. However, given their ability to accept type parameters, you have a few additional factors to keep in mind when using a generic method for a delegate. This next set of examples demonstrate how generic methods can be used as part of a delegate. To get started, you'll need to create the following delegate and generic methods:

[VB code]
Public Delegate Sub MyDelegate(ByVal val1 As Int32, ByVal val2 As Double, _
                               ByVal z As String)

Public Sub DelegateMethod1(Of I, J, K)(ByVal val1 As I, ByVal val2 As J, _
                                       ByVal val3 As K)
End Sub

Public Sub DelegateMethod2(Of I, J, K)(ByVal val1 As Int32, ByVal val2 As Double, _
                                       ByVal val3 As String)
End Sub

Public Sub DelegateMethod3(Of I, J, K)()
End Sub
[C# code]
public delegate void MyDelegate(int val1, double val2, string val3);

public void DelegateMethod1<I, J, K>(I val1, J val2, K val3) {}
public void DelegateMethod2<I, J, K>(int val1, double val2, string val3) { }
public void DelegateMethod3<I, J, K>() { }

This example declares a single delegate that has a signature of integer, double, and string, respectively. It also has three variations of generic methods that it attempts to this delegate. The following declarations declare four separate instances of MyDelegate, each of which uses a flavor of the generic methods declared above: ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.