Generics and Collections


Generics really shine in the area of collections. The initial release of .NET had, among the thousands of possibly useful classes, a set of "collection" classes, all in the System.Collections namespace. Each collection lets you stuff as many other object instances as you want inside of that collection, and retrieve them later. The collections differ in how you stuff and retrieve, but they all allow you to stick any type of object in the collection.

One of the collection classes is the System.Collections.Stack class. Stacks let you store objects like pancakes: the first object you add to the stack goes on the bottom, and each one you add goes on top of the previous object. When you're ready to eat a pancakeI mean, remove an itemit comes off the top. The Push and Pop methods manage the addition and removal of objects. (There is also a Peek method that looks at the top-most item, but doesn't remove it from the stack.)

Dim numberStack As New Collections.Stack numberStack.Push(10) numberStack.Push(20) numberStack.Push(30) MsgBox(numberStack.Pop())    ' Displays 30 MsgBox(numberStack.Pop())    ' Displays 20 MsgBox(numberStack.Pop())    ' Displays 10 


The thing with stacks (and other similar collections) is that you don't have to put just one type of object into the stack. You can mix any ol' type of objects you want.

Dim numberStack As New Collections.Stack numberStack.Push(10)                 ' Integer numberStack.Push("I'm sneaking in.") ' String numberStack.Push(Me.Button1)         ' Control 


The stack doesn't care, because it's just treating everything as System.Object. But what if you needed to ensure that only integers were put into the stack? What if you wanted to limit a stack to any specific data type, but didn't want to write separate stack classes for each possible type?

This sure sounds like a job for generics to me. It sounded that way to Microsoft, too. So they added a bunch of new generic collections to the Framework. They appear in the System.Collections.Generic namespace. There are a few different classes in this namespace, including classes for linked lists, queues, chocolate chip cookies, and dictionaries. And hey, there's a class called Stack(Of T). That's just what we need.

Dim numberStack As New Collections.Generic.Stack(Of Integer) numberStack.Push(10) numberStack.Push(20) numberStack.Push(30) 


Now, if we try to add anything other than an Integer to numberStack, an error occurs.

' ----- This won't work. numberStack.Push("I'll try again.") 





Start-to-Finish Visual Basic 2005. Learn Visual Basic 2005 as You Design and Develop a Complete Application
Start-to-Finish Visual Basic 2005: Learn Visual Basic 2005 as You Design and Develop a Complete Application
ISBN: 0321398009
EAN: 2147483647
Year: 2006
Pages: 247
Authors: Tim Patrick

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net