Stack Examples
This page was last reviewed on May 2, 2023.
Dot Net Perls
Stack. In a stack, each element is added to the top. Each element we remove is removed from the top. This is a LIFO collection—the stack is last-in-first-out.
The C# Stack can help us develop parsers quickly. It can replace recursive algorithms. Stack is a generic type—we must specify its stored element type.
Push. Usually the first action we need to do on Stack is Push elements into it. The word Push is a term that means "add to the top." Here we create a Stack.
Step 1 A local variable is assigned to a new Stack containing 3 integers. The ints were added with the 10000 last.
Step 2 We write each value of the stack to the Console in a foreach-loop with Console.WriteLine.
Tip We see that 10000 is displayed first. This is explained by the LIFO concept—last in, first out.
Tip 2 The last element added (with Push) to Stack is the first one removed (with Pop).
using System; using System.Collections.Generic; // Step 1: create new stack. var stack = new Stack<int>(); stack.Push(100); stack.Push(1000); stack.Push(10000); // Step 2: display stack. Console.WriteLine("--- Stack contents ---"); foreach (int i in stack) { Console.WriteLine(i); }
--- Stack contents --- 10000 1000 100
Pop, Peek. Here we call more Stack methods. Pop and Peek both act on the top of Stack, meaning the element most recently added. They also both return that top value.
Tip When we call Pop, the elements from the top of the Stack is returned, and the element is removed from the collection.
Tip 2 Peek() does not remove the element from the Stack collection. It only gets the value—it "peeks" at the value.
using System; using System.Collections.Generic; // Get the stack. var stack = new Stack<int>(); stack.Push(100); stack.Push(1000); stack.Push(10000); // Pop the top element. int pop = stack.Pop(); // Write to the console. Console.WriteLine("--- Element popped from top of Stack ---"); Console.WriteLine(pop); // Now look at the top element. int peek = stack.Peek(); Console.WriteLine("--- Element now at the top ---"); Console.WriteLine(peek);
--- Element popped from top of Stack --- 10000 --- Element now at the top --- 1000
Clear, Count. Let us test more parts of Stack. The Count property is used without parentheses, while Clear() is a parameterless method. It erases the Stack's contents.
Note The example receives the Stack used in the above examples, then counts it, clears it, and finally counts it again.
using System; using System.Collections.Generic; // Get the stack. var stack = new Stack<int>(); stack.Push(100); stack.Push(1000); stack.Push(10000); // Count the number of elements in the Stack int count = stack.Count; Console.WriteLine("--- Element count ---"); Console.WriteLine(count); // Clear the Stack stack.Clear(); Console.WriteLine("--- Stack was cleared ---"); Console.WriteLine(stack.Count);
--- Element count --- 3 --- Stack was cleared --- 0
Exceptions. When you call Pop or Peek on your Stack, the runtime will throw an exception if the Stack has zero elements. This can be solved.
Tip To work around this problem, you must check the Count property. Here we catch the exception raised by this situation.
using System; using System.Collections.Generic; class Program { static void Main() { // Create an empty Stack. var stack = new Stack<int>(); try { // This throws an exception. int pop = stack.Pop(); } catch (Exception ex) { Console.WriteLine("--- Exception raised by Pop ---"); Console.WriteLine(ex.ToString()); } // Here we safely Pop the stack. if (stack.Count > 0) { int safe = stack.Pop(); } else { Console.WriteLine("--- Avoided exception by using Count method ---"); } } }
--- Exception raised by Pop --- System.InvalidOperationException: Stack empty. ... ... --- Avoided exception by using Count method
Copy, search. You can use constructors of Stack to streamline your code. One constructor accepts an IEnumerable parameter, which is an interface that most collections implement.
Also We search the Stack with the Contains method. The Contains method on Stack returns true if the element is found.
true, false
Detail With Contains we search for a string. The object reference is not compared. Instead the string contents are.
using System; using System.Collections.Generic; // An example string array. string[] values = { "Dot", "Net", "Perls" }; // Copy an array into a Stack. var stack = new Stack<string>(values); // Display the Stack. Console.WriteLine("--- Stack contents ---"); foreach (string value in stack) { Console.WriteLine(value); } // See if the stack contains "Perls" Console.WriteLine("--- Stack Contains method result ---"); bool contains = stack.Contains("Perls"); Console.WriteLine(contains);
--- Stack contents --- Perls Net Dot --- Stack Contains method result --- True
Null. The value null is allowed in Stacks with reference types such as string. You can also assign your Stack to null instead of calling Clear.
Discussion. There are several other methods on Stack in System.Collections.Generic. You can copy your Stack to a new array with ToArray(). Also, you can use TrimExcess to reduce memory.
Info TrimExcess will check the Stack's fill rate, and then resize the internal array.
Also When looking inside Stack with IL Disassembler, we see it is implemented with an array of type T[]. This is type you specify.
The Stack collection, found in the System.Collections.Generic namespace, provides a wrapper on an array. Stack is a useful abstraction of the classic stack data structure.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 2, 2023 (rewrite).
© 2007-2024 Sam Allen.