5.2. A Deeper Look
With the conceptual introduction behind us, let's now consider some more detailed examples of generic methods. The following example defines a class, SimpleClass, which declares a series of generic methods that illustrate some of the variations that are available to you when creating your own generic methods. To make things more interesting, all of these generic methods in this example are placed within a generic class. The code for the class is as follows:
[VB code] Public Class SimpleClass(Of T, U) Private _outerVal1 As T Private _outerVal2 As U Public Sub New(ByVal val1 As T, ByVal val2 As U) Me._outerVal1 = val1 Me._outerVal2 = val2 End Sub Public Sub Foo1(Of I)(ByVal innerVal As I) Console.Out.WriteLine("Method Param Type : {0}", innerVal.GetType()) Console.Out.WriteLine("Class Param Type(T): {0}", _outerVal1.GetType()) End Sub Public Function Foo2(Of I)(ByVal innerVal As I) As U Console.Out.WriteLine("Method Param Type : {0}", innerVal.GetType()) Console.Out.WriteLine("Method Return Type(U): {0}", _outerVal1.GetType()) Return _outerVal2 End Function Public Sub Foo3(Of T)(ByVal innerVal As T) Console.Out.WriteLine("Method Param Type : {0}", innerVal.GetType()) End Sub Public Shared Function Foo4(Of I, J)(ByVal val1 As I, ByVal val2 As J, _ ByVal outer As U) As Nullable(Of T) Dim retVal As New Nullable(Of T) Console.Out.WriteLine("Static Method Param1 Type : {0}", val1.GetType())
Console.Out.WriteLine("Static Method Param2 Type : {0}", val2.GetType()) Console.Out.WriteLine("Static ...
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.