
.NET 1.1+The Stack Collection
The forty-first part of the C# Fundamentals tutorial examines the Stack class. This collection includes the functionality required in a 'Last In, First Out' (LIFO) stacking structure. Stacks allow items to be held for later extraction and processing.
What is a Stack?
Stacks are similar in structure to queues. However, where a queue ensures that the items are extracted from the collection in the order they were added, stacks allow the most recently added items to be retrieved first. This is known as Last In, First Out or LIFO.
Operating systems and high-level development languages frequently use stacks. One key use is when storing the return points for program calls. Each time a subroutine is called, the address of the calling function is added, or pushed, onto the stack. When the subroutine terminates, the last address can be retrieved, or popped, from the stack and normal program flow can continue from the previous location. The earlier C# Exception Handling article includes an example of the use of a stack when reading the StackTrace property.
The Stack Collection
The .NET framework includes the Stack class. This provides all of the functionality required to operate LIFO stacks with no additional code. The Stack class provides a simple collection that can contain any type of object, including duplicates and nulls.
Implemented Collection Interfaces
The Stack collection implements the properties and methods of the ICollection interface. This was described in the earlier Collection Interfaces article. The rest of this article describes the additional functionality provided by Stack.
Declaring a Stack
Constructors
The Stack class has three constructors. The first requires no parameters. It creates an empty stack with the capacity to store up to ten items. Should an eleventh item be added, the capacity of the stack is automatically doubled. It doubles again each time the capacity of the stack is exceeded.
The Stack class is found in the System.Collections namespace so add using System.Collections; to the source code.
Stack myLifo = new Stack();
If the maximum number of items that will be stored in a Stack is known before the collection is created, it is more efficient to declare the capacity. If the size is underestimated the size of the stack will still doubled to accommodate extra items. To declare the initial size of a Stack, pass the capacity to the constructor as an integer parameter.
Stack myLifo = new Stack(15);
The third constructor permits the creation of a pre-populated stack containing the objects from any class that implements ICollection.
ArrayList myList = new ArrayList();
myList.Add("String 1");
myList.Add("String 2");
Stack myLifo = new Stack(myList); // Copies myList into the stack
17 June 2007