C# Stack
Stack
Think of a stack of plates. You put a new plate on the top. When you need a plate, you take the one on the top. The last plate you put on is the first plate you take off.
A Stack in C# works the same way. This is called last in, first out (LIFO).
You use stacks every day: the Undo button in a text editor undoes your last change first, then the change before that, and so on.
Like List, Stack is in the System.Collections.Generic namespace:
Example
// Include the namespace that holds Stack
using System.Collections.Generic;
Push and Peek
Push() puts an item on the top of the stack. Peek() returns the top item, without removing it:
Example
Stack<string> cars = new Stack<string>();
cars.Push("Volvo");
cars.Push("BMW");
cars.Push("Ford");
cars.Push("Mazda");
Console.WriteLine(cars.Peek()); // Mazda
Mazda was pushed last, so it is on the top.
Pop Items
Pop() removes the top item and returns it. Count tells you how many items are left:
Example
Stack<string> cars = new Stack<string>();
cars.Push("Volvo");
cars.Push("BMW");
cars.Push("Ford");
Console.WriteLine(cars.Pop()); // Ford
Console.WriteLine(cars.Peek()); // BMW
Console.WriteLine(cars.Count); // 2
Loop Through a Stack
A foreach loop goes through the stack from the top to the bottom. It does not remove any items:
Example
Stack<string> cars = new Stack<string>();
cars.Push("Volvo");
cars.Push("BMW");
cars.Push("Ford");
foreach (string car in cars)
{
Console.WriteLine(car);
}
Ford was pushed last, so it comes first.
Example: Undo
A text editor can save each change in a stack. When you click Undo, it pops the last change:
Example
Stack<string> changes = new Stack<string>();
changes.Push("Type Hello");
changes.Push("Make the text bold");
changes.Push("Change the color to red");
Console.WriteLine("Undo: " + changes.Pop());
Console.WriteLine("Undo: " + changes.Pop());
Console.WriteLine("Changes left: " + changes.Count);
The last change (the red color) is undone first, then the bold text. Only "Type Hello" is left in the stack.