Skip to Main Content
Professional Visual Studio® 2008
book

Professional Visual Studio® 2008

by Nick Randolph, David Gardner
July 2008
Intermediate to advanced content levelIntermediate to advanced
1026 pages
27h 59m
English
Wrox
Content preview from Professional Visual Studio® 2008

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Professional Visual Studio® 2010

Professional Visual Studio® 2010

Nick Randolph, David Gardner, Michael Minutillo, Chris Anderson

Publisher Resources

ISBN: 9780470229880Purchase book