1. Home
  2. Computing & Technology
  3. Visual Basic

Generics in Action

By Dan Mabbutt, About.com

The easiest way to start learning about generics is to use one of the generic datatypes that have been added to .NET Framework 2.0. Starting with the basics, the thing to look for that tells you that you're dealing with generic types is the Of keyword. It can be present in a lot of 2.0 statements. Some examples:

In a Class statement:

Public Class myClass(Of T)
   Dim myVal As T
End Class

In a Structure statement:

Public Structure myStruct(Of T)
   Dim myVal As T
End Structure

In a Sub:

Public Sub callTestSub()
   testSub(Of String)("A String")
   testSub(Of Integer)(5)
End Sub

Public Sub testSub(Of T)(ByVal arg As T)
   Dim a As T
   a = arg
   MessageBox.Show(a.ToString)
End Sub

You can also use generics in Delegates, Functions, and Interfaces.

The examples above all use the variable T as the generic placeholder. The use of T isn't required (the last example here doesn't use it), but it's traditional and you see it a lot in Microsoft documentation. You could use another variable name.

The easiest way to introduce generics in an actual code example is to use one of the generic types that have been added to the System.Collections.Generic namespace. These are types that accept generic placeholders (like Of T) as arguments. It's worth checking out this namespace in the Visual Studio Object Browser.

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

The traditional example, used by Microsoft in their seminars, is to start with a Framework 1.X ArrayList object for comparison. The following code shows that you can add any datatype to the ArrayList.

Dim myArrayList As ArrayList = New ArrayList()
myArrayList.Add(1)
myArrayList.Add(2)
myArrayList.Add(3)
myArrayList.Add("Ain't ArrayList Great!")

This works pretty well ... except when it comes time to do something with the ArrayList.

Dim total As Integer = 0
Dim val As Integer
For Each val In myArrayList
   total = total + val
Next

As the illustration below shows, strings and integers don't mix when you try to add them.

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

Explore Visual Basic

More from About.com

  1. Home
  2. Computing & Technology
  3. Visual Basic
  4. VB Books
  5. VB.NET Special Topics
  6. Generics! Cleaner Data - Faster Code!

©2008 About.com, a part of The New York Times Company.

All rights reserved.