This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.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


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

Using Stack Functions

Push Method

Stacks allow new items to be added to the top of the stack and later be extracted in the reverse order to their addition. To add a new item to the top of the stack, use the Push method. This method accepts one parameter, being the object to add to the stack.

Stack breadcrumbs = new Stack();

breadcrumbs.Push("Home Page");

Console.WriteLine("Count: {0}", breadcrumbs.Count);     // Outputs "Count: 3"

Pop Method

To retrieve items from a stack you call the Pop method. Pop returns the item from the top of the stack and removes it from the collection. The item is returned as an object that can be cast to the correct type. In the following example, the ToString method is used to perform the conversion as three items are added to and then retrieved from a stack. Not that the order of extraction is the reverse of the order in which the items were pushed onto the stack.

Stack breadcrumbs = new Stack();

breadcrumbs.Push("Home Page");

while (breadcrumbs.Count != 0)
    string next = breadcrumbs.Pop().ToString();


Home Page


Peek Method

It can be useful to obtain the next item in a stack without removing it from the collection. The Peek method is used in the same manner as Pop but when the top item is retrieved, it is also left in position.

Stack breadcrumbs = new Stack();

breadcrumbs.Push("Home Page");

string next = breadcrumbs.Peek().ToString();
Console.WriteLine(next);                                // Outputs "C#"
Console.WriteLine("Count: {0}", breadcrumbs.Count);     // Outputs "Count: 3"
17 June 2007