C# Stack with Examples

In c#, Stack is useful for representing a collection of objects that store elements in LIFO (Last in, First out) style, i.e., the element that is added last will be the first to come out.

 

Generally, stacks are useful when you want to access elements from the collection in a last-in-first-out style, and we can store multiple null and duplicate values in a stack based on our requirements.

 

By using Push() and Pop() / Peek() methods, we can add or retrieve elements from the stack. Here, the Push() method is useful to add elements to the stack, and the Pop() / Peek() method is useful to retrieve elements from the stack.

 

Following is the pictorial representation of the stack process flow in the c# programming language.

 

C# Stack Process Flow Diagram

C# Stack Declaration

Generally, c# will support both generic and non-generic types of stacks. Here, we will learn about non-generic queue collections by using the System.Collections namespace so you can add elements of different data types.

 

As discussed, the collection is a class, so to define a stack, you need to declare an instance of the stack class before we perform any operations like add, delete, etc. as shown below.

 

Stack stk = new Stack();

If you observe the above stack declaration, we created a new stack (stk) with an instance of stack class without specifying any size.

C# Stack Properties

The following are some of the commonly used properties of a stack in the c# programming language.

 

PropertyDescription
Count It will return the total number of elements in a stack.
IsSynchronized It is used to get a value to indicate whether access to the stack is synchronized (thread-safe) or not.

C# Stack Methods

The following are some of the commonly used stack methods to perform operations like add, delete, etc., on elements of a stack in the c# programming language.

 

MethodDescription
Push It is used to insert an object at the top of a stack.
Pop It will remove and return an object at the top of the stack.
Clear It will remove all the elements from the stack.
Clone It will create a shallow copy of the stack.
Contains It is used to determine whether an element exists in a stack or not.
Peek It is used to return a top element from the stack.

C# Stack Example

Here, we will use a non-generic collection of the stack to add elements of different data types to the stack using Push() method. Following is the example of adding and accessing elements of the stack in c#.

 

using System;
using System.Collections;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          // Create and initialize a stack
          Stack stk = new Stack();
          stk.Push("Welcome");
          stk.Push("Tutlane");
          stk.Push(20.5f);
          stk.Push(10);
          stk.Push(null);
          stk.Push(100);
          Console.WriteLine("Number of Elements in Stack: {0}", stk.Count);
          Console.WriteLine("******Stack Elements******");
          // Access Stack Elements
          foreach (var item in stk)
          {
             Console.WriteLine(item);
          }
          Console.ReadLine();
       }
    }
}

If you observe the above example, we created a new stack (stk) and added different data type elements to the stack (stk) using Push() method, and we used a foreach loop to iterate through the stack to get elements from it.

 

When you execute the above c# program, you will get the result below.

 

C# Add Elements to Stack Example Result

 

If you observe the above result, we got elements from the stack in LIFO (last in, first out) order.

C# Stack Pop() Method to Access Elements

As discussed, the stack Pop() method will always remove and return a top element of the queue. Following is the example of accessing stack elements using the Pop() method in c#.

 

using System;
using System.Collections;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          // Create and initialize a stack
          Stack stk = new Stack();
          stk.Push("Welcome");
          stk.Push("Tutlane");
          stk.Push(20.5f);
          stk.Push(10);
          stk.Push(null);
          stk.Push(100);
          Console.WriteLine("Number of Elements in Stack: {0}", stk.Count);
          Console.WriteLine("******Stack Elements******");
          // Access Stack Elements
          while (stk.Count > 0)
          {
             Console.WriteLine(stk.Pop());
          }
          Console.WriteLine("Number of Elements in Stack: {0}", stk.Count);
          Console.ReadLine();
       }
    }
}

If you observe the above example, we are accessing stack elements by using the Pop() method, and calling a Pop method on an empty stack will throw an exception (InvalidOperation), so to avoid that situation, we are checking whether the count of stack elements greater than zero or not using while loop.

 

When you execute the above c# program, you will get the result below.

 

C# Pop Method to Access Elements Example Result

 

If you observe the above result, every time the Pop() method has removed and returned a top element of the stack that’s the reason at the end we got a count of stack elements as 0.

 

If you want to remove all the elements of the stack, you need to use a clear() method.

C# Stack Peek() Method to Access Elements

As discussed, the stack Peek() method will always return the last (top-most) inserted element of the stack. Following is the example of accessing stack elements using the Peek() method in c#.

 

using System;
using System.Collections;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          // Create and initialize a stack
          Stack stk = new Stack();
          stk.Push("Welcome");
          stk.Push("Tutlane");
          stk.Push(20.5f);
          stk.Push(10);
          stk.Push(null);
          stk.Push(100);
          Console.WriteLine("Number of Elements in Stack: {0}", stk.Count);
          Console.WriteLine("******Stack Elements******");
          // Access Stack Elements
          Console.WriteLine(stk.Peek());
          Console.WriteLine(stk.Peek());
          Console.WriteLine(stk.Peek());
          Console.WriteLine("Number of Elements in Stack: {0}", stk.Count);
          Console.ReadLine();
       }
    }
}

If you observe the above example, we are accessing stack elements by using Peek() method.

 

When you execute the above c# program, we will get the result below.

 

C# Stack Peek Method Example Result

 

If you observe the above result, every time the Peek() method has returned the last (top-most) element of the queue without removing any element, that’s the reason at the end also the stack elements count is same as the starting of the stack.

C# Stack Contains() Method

In c#, by using the stack Contains() method, we can check whether an element exists in a stack or not. In case if the element is found in the stack, then it will return true otherwise false.

 

Following is the example of using the stack Contains() method to check whether an item exists in a stack or not in c#.

 

using System;
using System.Collections;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          // Create and initialize a stack
          Stack stk = new Stack();
          stk.Push("Welcome");
          stk.Push("Tutlane");
          stk.Push(20.5f);
          stk.Push(10);
          stk.Push(null);
          stk.Push(100);
          Console.WriteLine("******Stack Example******");
          Console.WriteLine("Contains Element 4: {0}", stk.Contains(4));
          Console.WriteLine("Contains Element 100: {0}", stk.Contains(100));
          Console.WriteLine("Contains Key 'Hello': {0}", stk.Contains("Hello"));
          Console.ReadLine();
       }
    }
}

If you observe the above example, we used a Contains() method to check for particular elements that exist in the stack (stk) or not.

 

When we execute the above c# program, we will get the result below.

 

C# Stack Contains() Method Example Result

C# Stack Overview

The following are important points that need to remember about the stack in c#.

 

  • In c#, stacks are used to store a collection of objects in a LIFO (Last in, First out) style, i.e., the element which added last will come out first.
  • By using the Push() method, you can add elements to the stack.
  • The Pop() method will remove and return a topmost element from the stack.
  • The stack Peek() method will always return the last (top-most) inserted element of the stack, and it won’t delete any element from the stack.