11.6. Exact Run-Time Types

The .NET generics implementation attempts to make generic types behave like any other type you might employ. This means that the marriage of a generic type and its type arguments should represent an actual type that can be evaluated like any other type. Consider the following example:

[VB code]
Public Class TestClass1(Of T)
End Class

Public Class TestClass2(Of T)
End Class

Public Class TestExactTypes

    Public Sub CompareTypes()
        Dim type1 As New TestClass1(Of Int32)
        Dim type2 As New TestClass1(Of String)
        Dim type3 As New TestClass2(Of Int32)

        CompareTypes(type1)
        CompareTypes(type2)
        CompareTypes(type3)
    End Sub

    Public Sub CompareTypes(ByVal aType As Object)
        If (TypeOf (aType) Is TestClass1(Of Int32)) Then
            Console.Out.WriteLine("Instance of TestClass1(Of Int32)")
        ElseIf (TypeOf (aType) Is TestClass1(Of String)) Then
            Console.Out.WriteLine("Instance of TestClass1(Of String)")
        ElseIf (TypeOf (aType) Is TestClass1(Of Double)) Then
            Console.Out.WriteLine("Instance of TestClass1(Of Double)")
        ElseIf (TypeOf (aType) Is TestClass2(Of Int32)) Then
            Console.Out.WriteLine("Instance of TestClass2(Of Int32)")
        End If
    End Sub
End Class
[C# code]
public class TestClass1<T> { }

public class TestClass2<T> { }

public class TestExactTypes {
    public void CompareTypes() {
        TestClass1<int> type1 = new TestClass1<int>();
        TestClass1<string> type2 = new TestClass1<string>();
        TestClass2<int> type3 = new TestClass2<int>();

        CompareTypes(type1);
        CompareTypes(type2);
        CompareTypes(type3);
    }

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.