oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

What Are Generics

by Jesse Liberty, author of Programming Visual Basic 2005

Generics provide the ability to create type-safe collections in .NET. The best way to understand Generics is to understand the problem they were designed to solve.

In This Article:

  1. Why Type Safety Is Important
  2. Solving the Problem with Generics
  3. Type-Safe Collections

In .NET 1.x, the built-in collections (e.g., ArrayList, Queue, Stack, Dictionary) were not type-safe. Each of these collections took an Object, and since everything in .NET derives from Object, this meant that each collection would take any instance of any type. Thus, you could comfortably write code that looked like this: [1]

      Dim myArrayList As New ArrayList()
      For i As Integer = 0 To 20

The snippet above creates an ArrayList and adds 21 Integers to it. Unfortunately, there is nothing in the ArrayList to prevent you from writing:

      Dim myString As String = "Uh oh, I'm not an Integer"

You now have an ArrayList with Integers and a String in it. The technical term for this is "bad." The ArrayList is not type-safe.

Why Type Safety Is Important

Type safety enlists the compiler in finding your bugs. I used to work for a guy named Pat Johnson who said "Save time debugging, don't put any bugs in." Despite that bit of wisdom, most sizable applications have some bugs at first, and, given the choice, you want compile-time bugs rather than run-time bugs. This is because compile time bugs will be found 100 percent of the time you compile your code, while run-time bugs can and will hide in the crevices and interstices of your program; waiting, biding their time, living silently on morsels of syntax until you ship your program, when they will spring out, cackling madly in front of your customers.

There are two other programs with ArrayList-holding objects. First, any time you take an object out, you need to cast it to its "real" type (the collection only knows it is an Object, not that it is an Integer); and second, because you cannot know for sure what is actually in the ArrayList, you find yourself writing code that checks the type of the object before casting it.:

sum = 0
For Each tmpObject As Object In myArrayList
   If TypeOf tmpObject Is Integer Then
      sum += CInt(tmpObject)   'cast to Integer
   End If

This code adds all the Integer values in myArrayList, but since it is possible that there are other types in that list (strings, Dogs, Monsters), it must first check the type of each entry to make sure it is an Integer. This makes for ugly code that is error prone and hard to maintain.

C# 1.x and VB.NET programmers cried out for help, "We want a grownup programming language that has type-safe collections." C# 2.0 and Visual Basic 2005 provide the solution with Generics.

Pages: 1, 2

Next Pagearrow