Home
VB.NET
Generic Class
This page was last reviewed on Jul 20, 2024.
Dot Net Perls
Generics. Suppose we want to make a class that stores 10 values, but we do not know what the exact type of the values should be. We can turn this class into a generic class.
Class
With an Of-clause, we can specify a type parameter on a Class, creating a generic class. Then when we create an instance of the Class, we must specify that type.
Example. This VB.NET program introduces a Test class that has 1 type parameter. Test is a generic class—it must be used with a type parameter in Main.
Version 1 We create an instance of the Test class with a Boolean type parameter. The code should only be used with Boolean values (in place of T).
Version 2 Here we use the Test class with an Integer parameter. This satisfies the Structure constraint (which refers to a value type).
Warning In VB.NET, some of the type checking is not strict—the program will compile if the types used do not match with the type parameter.
So Generic types can be created in VB.NET, but for optimal support of generic type compilation, C# is a better choice.
' Specify the T must be a value type like Integer, Boolean, etc. Class Test(Of T As {Structure}) ' Store array of 10 values of the generic type of elements. Dim _values(9) As T Public Sub SetValueAt(i As Integer, v As T) If i >= 0 AndAlso i < _values.Length _values(i) = v End If End Sub Public Function GetValueAt(i As Integer) As T If i >= 0 AndAlso i < _values.Length Return _values(i) End If Return _values(0) End Function End Class Module Module1 Sub Main() ' Version 1: use generic class with Boolean parameter. Dim t As Test(Of Boolean) = New Test(Of Boolean) t.SetValueAt(5, True) Dim result As Boolean = t.GetValueAt(5) Console.WriteLine(result) ' Version 2: use generic class with Integer parameter. Dim t2 = New Test(Of Integer) t2.SetValueAt(3, 100) Console.WriteLine(t2.GetValueAt(3)) End Sub End Module
True 100
Constraints. Notice the "Structure" keyword in the Test class generic type. This is a type constraint. Structure means a value type, like Integer or DateTime.
Next Try changing the keyword Structure to "New" to require that a class with a constructor be used.
Further You can specify an interface like IDisposable as a constraint—all instances must use a type argument that implements the interface.
Summary. Usually custom generic types are not needed in VB.NET programs, but this feature can occasionally improve programs. Types like List and Dictionary are generics that are built into .NET.
List
Dictionary
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 20, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.