O'Reilly logo

Professional .NET 2.0 Generics by Tod Golding

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required