C# Stack with Examples

In c#, Stack is used to represent a collection of objects which stores an elements in LIFO (Last in, First out) style i.e. the element which added last will be the first to come out.

 

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

 

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

 

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

 

C# Stack Process Flow Diagram

C# Stack Declaration

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

 

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

 

Stack stk = new Stack();

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

C# Stack Properties

Following are the some of commonly used properties of stack in c# programming language.

 

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

C# Stack Methods

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

 

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

C# Stack Example

Here, we are going to use non-generic collection of stack so we can add an elements of different data types to the stack using Push() method. Following is the example of adding and accessing an 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 above example, we created a new stack (stk) and added a different data type elements to the stack (stk) using Push() method and we used a foreach loop to iterate through the stack to get an elements from it.

 

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

 

C# Add Elements to Stack Example Result

 

If you observe above result, we got an 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 a stack elements using 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 above example, we are accessing a stack elements by using Pop() method and calling a Pop method on 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 we execute above c# program, we will get the result like as shown below.

 

C# Pop Method to Access Elements Example Result

 

If you observe 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.

 

In case, if you want to remove all the elements of stack, then you need to use clear() method.

C# Stack Peek() Method to Access Elements

As discussed, the stack Peek() method will always return a last (top-most) inserted element of the stack. Following is the example of accessing a stack elements using 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 above example, we are accessing a stack elements by using Peek() method.

 

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

 

C# Stack Peek Method Example Result

 

If you observe above result, every time the Peek() method has returned a 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 starting of the stack.

C# Stack Contains() Method

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

 

Following is the example of using stack Contains() method to check whether an item exists in 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 above example, we used a Contains() method to check for a particular elements exists in stack (stk) or not.

 

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

 

C# Stack Contains() Method Example Result

C# Stack Overview

Following are important points which needs to remember about 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 Push() method, we can add an elements to the stack.
  • The Pop() method will remove and return a top most element from the stack.
  • The stack Peek() method will always return a last (top-most) inserted element of the stack  and it won’t delete any element from the stack.
 

NEXT

Generics in C#