C# Generic Stack

A generic stack in C# is much like its non-generic counterpart. They can be described as a last-in first-out data structure, or LIFO for short. New elements are added to the top of the stack and the last element added is the first element available to be removed. The generic version, discussed here, however, must have the type of data it stores specified when it is declared.

Below is an example of how a stack, called ‘people’, that contains string values, can be declared.

Stack<string> people = new Stack<string>();

In order to add items to a stack, the ‘Push’ method must be used.


Here, four names have been added to the stack.

It is possible to see how many items there are in the stack using the ‘Count’ property of the stack itself.


In order to see the items in a generic stack, without actually removing them, a ‘foreach’ loop can be used.

foreach (string person in people)

This will display each name in the stack on a separate line in the console, in the order that the values will be removed, the reverse of how they were added.


If it is required to see just the next item in the stack without removing it, then the ‘Peek’ method can be used.


As well as being able to see the next item, there is also the functionality to check to see if a particular value exists in a stack. This is achieved using the ‘Contains’ method.


The above example checks to see if the value, ‘George’, exists in the stack and returns a Boolean 'True' or 'False' value.

In order to remove individual items from a stack, the ‘Pop’ method can be utilised. The example below assigns the number of items in the stack to a variable. This value is then used to limit the number of iterations in a ‘for’ loop. Within the loop the ‘Pop’ method is used to remove an item from the stack, display it in the console and output the number of items left in the stack.

Stack<string> people = new Stack<string>();


int stackHeight = people.Count;

Console.WriteLine("Items in stack: {0}", stackHeight);

for (int i = 1; i <= stackHeight; i++)

   Console.WriteLine("Next item from stack: {0}", people.Pop());
   Console.WriteLine("Items left in stack: {0}", people.Count);


The resulting output is shown below.

Items in stack: 4

Next item from stack: Alan
Items left in stack: 3

Next item from stack: Fred
Items left in stack: 2

Next item from stack: George
Items left in stack: 1

Next item from stack: Bob
Items left in stack: 0

Finally, if it is necessary to remove all items in a stack in one go, instead of individually with the ‘Pop’ method, there is a ‘Clear’ method to accomplish this.


Further Reading