NamespaceSystem.Collections (standard version) System.Collections.Generic (generic version) CreatableYes DescriptionThe Stack object implements a "last in, first out" (LIFO) data structure. Items are added to the top of the stack, and new items are placed "on top" of the previously added items. Only the current topmost item can be removed. A real-life parallel would be a stack of books or a stack of pancakes. The stack includes features for adding items (Push), removing items (Pop), and counting the items in the stack (Count), among other features. Objects of any type may be added to the stack. The following table lists some of the more useful and interesting members of the Stack class. Those marked with an asterisk (*) have separate entries in this chapter.
ExampleThis sample code shows the basic use of the stack. ' ----- Add some basic items to a stack. Dim nameStack As New Stack nameStack.Push("Chopin") nameStack.Push("Mozart") nameStack.Push("Beethoven") ' ----- Examine and return the items. MsgBox(nameStack.Peek( )) ' Displays "Beethoven" MsgBox(nameStack.Pop( )) ' Displays "Beethoven" MsgBox(nameStack.Pop( )) ' Displays "Mozart" ' ----- Remove the remaining items. MsgBox(nameStack.Count) ' Displays 1 (for Chopin) nameStack.Clear( ) Version DifferencesVisual Basic 2005 adds support for generics to several collection-style classes, including the Stack class. The version of the Stack class that supports generics appears in the System.Collections.Generic namespace. Generics are discussed in Chapter 10. See AlsoCollection Class, Hashtable Class, Queue Class |