GENERICS

Chapter 26 explains how you can build and use generic classes to perform similar actions for objects of various types. For example, you could build a Tree class that can build a tree of any specific kind of object. Your program could then make a tree of Employees, a tree of Customers, a tree of Punchlines, or even a tree of trees. Visual Basic comes with a useful assortment of prebuilt generic collection classes.

The System.Collections.Generic namespace provides several generic collection classes that you can use to build strongly typed collections. These collections work with a specific data type that you supply in a variable’s declaration. For example, the following code makes a List that holds strings:

Imports System.Collections.Generic
 
...
Dim places As New List(Of String)
places.Add("Chicago")

The places object’s methods are strongly typed and work only with strings, so they provide extra error protection that a less specialized collection doesn’t provide. To take advantage of this extra protection, you should use generic collections whenever possible.

You cannot directly modify a generic collection class, but you can add extension methods to it. For example, the following code adds an AddPerson method to the generic List(Of Person) class. This method takes as parameters a first and last name, uses those values to make a Person object, and adds it to the list.

Module PersonListExtensions <Extension()> Public Sub AddPerson(person_list As List(Of Person), first_name ...

Get Visual Basic 2012 Programmer's Reference 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.