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
.
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.
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
.
class
with a Boolean
type parameter. The code should only be used with Boolean
values (in place of T).class
with an Integer parameter. This satisfies the Structure
constraint (which refers to a value type).' 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 ModuleTrue 100
Notice the "Structure
" keyword in the Test class
generic type. This is a type constraint. Structure
means a value type, like Integer or DateTime
.
Structure
to "New" to require that a class
with a constructor be used.interface
like IDisposable
as a constraint—all instances must use a type argument that implements the interface
.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.