Share via


How to: Use a Generic Class (Visual Basic)

A class that takes type parameters is called a generic class. If you are using a generic class, you can generate a constructed class from it by supplying a type argument for each of these parameters. You can then declare a variable of the constructed class type, and you can create an instance of the constructed class and assign it to that variable.

In addition to classes, you can also define and use generic structures, interfaces, procedures, and delegates.

The following procedure takes a generic class defined in the .NET Framework and creates an instance from it.

To use a class that takes a type parameter

  1. At the beginning of your source file, include an Imports Statement (.NET Namespace and Type) to import the System.Collections.Generic namespace. This allows you to refer to the System.Collections.Generic.Queue<T> class without having to fully qualify it to differentiate it from other queue classes such as System.Collections.Queue.

  2. Create the object in the normal way, but add (Of type) immediately after the class name.

    The following example uses the same class (System.Collections.Generic.Queue<T>) to create two queue objects that hold items of different data types. It adds items to the end of each queue and then removes and displays items from the front of each queue.

    Public Sub usequeue()
      Dim queueDouble As New System.Collections.Generic.Queue(Of Double)
      Dim queueString As New System.Collections.Generic.Queue(Of String)
      queueDouble.Enqueue(1.1)
      queueDouble.Enqueue(2.2)
      queueDouble.Enqueue(3.3)
      queueDouble.Enqueue(4.4)
      queueString.Enqueue("First string of three")
      queueString.Enqueue("Second string of three")
      queueString.Enqueue("Third string of three")
      Dim s As String = "Queue of Double items (reported length " &
          CStr(queueDouble.Count) & "):" 
      For i As Integer = 1 To queueDouble.Count
        s &= vbCrLf & CStr(queueDouble.Dequeue())
      Next i
      s &= vbCrLf & "Queue of String items (reported length " &
          CStr(queueString.Count) & "):" 
      For i As Integer = 1 To queueString.Count
        s &= vbCrLf & queueString.Dequeue()
      Next i
      MsgBox(s)
    End Sub
    

See Also

Tasks

How to: Define a Class That Can Provide Identical Functionality on Different Data Types (Visual Basic)

Reference

Of Clause (Visual Basic)

Imports Statement (.NET Namespace and Type)

Concepts

Data Types in Visual Basic

Generic Types in Visual Basic (Visual Basic)

Language Independence and Language-Independent Components

Other Resources

Iterators (C# and Visual Basic)