11.1. Generics

For anyone unfamiliar with templates in C++ or the concept of a generic type, this section begins with a simple example that illustrates where a generic can replace a significant amount of coding, while also maintaining strongly typed code. This example stores and retrieves integers from a collection. As you can see from the following code snippet, there are two ways to do this: either using a non-typed ArrayList, which can contain any type, or using a custom-written collection:

'Option 1 - Non-typed Arraylist
'Creation - unable to see what types this list contain
Dim nonTypedList As New ArrayList
'Adding - no type checking, so can add any type
nonTypedList.Add(1)
nonTypedList.Add("Hello")
nonTypedList.Add(5.334)
'Retrieving - no type checking, must cast (should do type checking too)
Dim output As Integer = CInt(nonTypedList.Item(1))
'Option 2 - Strongly typed custom written collection
'Creation - custom collection
Dim myList As New IntegerCollection
'Adding - type checking, so can only add integers
myList.Add(1)
'Retrieving - type checking, so no casting required
output = myList.Item(0)

Clearly, the second approach is preferable because it ensures that you put only integers into the collection. However, the downside of this approach is that you have to create collection classes for each type you want to put in a collection. You can rewrite this example using the generic List class:

'Creation - generic list, specifying the type of objects it contains Dim genericList ...

Get Professional Visual Studio® 2008 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.