Non-Generic Stack in C#

Non-Generic Stack Collection Class in C# with Examples

In this article, I am going to discuss the Non-Generic Stack Collection Class in C# with Examples. Please read our previous article before proceeding to this article where we discussed the Non-Generic Collection Hashtable in C# with Examples. The Stack in C# represents a last-in, first-out collection of objects. That means it is used when we need last-in, first-out access to items. At the end of this article, you will understand the following pointers.

  1. What is Stack in C# and how does it work?
  2. Methods, Properties, and Constructor of Stack Class in C#
  3. How to create a Stack Collection in C#?
  4. How to Add Elements into a Stack in C#?
  5. How to Remove Elements from a Stack in C#?
  6. How to get the topmost element of a Stack in C#?
  7. How to check whether an element exists or not in the stack in C#?
  8. How to Clone the Non-Generic Stack Collection in C#?
  9. How to copy a stack to an existing array in C#?
  10. When to use Stack Collection in Real-time Applications in C#?
What is Stack in C# and how does it work?

The Stack in C# is a non-generic collection class that works in the LIFO(Last In First Out) principle. So, we need to use the Stack Collection in C#, when we need last in first out access to the items of a collection. That means the item which is added last will be removed first. When we add an item into the stack, then it is called pushing an item. Similarly, when we remove an item from the stack then it is called popping an item. The Stack class belongs to the System.Collections namespace.

Let us understand the LIFO principle with an example. Imagine we have a stack of plates with each plate added on top of each other. The last plate which is added to the stack will be the first one to remove from the stack. It is not possible to remove a plate from the middle of the stack.

In C#, the stack also works in the same way. Elements are added to the stack, one on the top of each other. When we add an item into the stack, then it is called pushing an item. The process of adding an element to the stack is called a push operation. Similarly, when we remove an item from the stack then it is called popping an item. This operation is known as pop. For a better understanding, please have a look at the below image.

What is Stack in C#

Note: Stack is defined as both generic and non-generic types of collection. The generic stack is defined in System.Collections.Generic namespace whereas non-generic stack is defined under System.Collections namespace. Here in this article, we will discuss the Non-Generic Stack Collection Class in C# with Examples.

Characteristics of Non-Generic Stack Collection Class in C#:
  1. The capacity of a Stack is the number of elements the Stack can hold. As we add elements to a Stack, the capacity of the stack is automatically increased.
  2. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation.
  3. The Stack Collection in C# allows both null and duplicate values.
Methods, Properties, and Constructor of Stack Class in C#:

If you go to the definition of Stack class, then you will see the following. As you can see the non-generic Stack class implements the IEnumerable, ICollection, and ICloneable interfaces.

Non-Generic Stack Collection Class in C#

How to create a Non-Generic Stack Collection in C#?

The non-generic collection Stack class in C# has three constructors which we can use to create a stack. The constructors are as follows:

  1. Stack(): It is used to initialize a new instance of the Stack class that is empty and has the default initial capacity.
  2. Stack(ICollection col): It is used to initialize a new instance of the non-generic Stack class that contains elements copied from the specified collection and has the same initial capacity as the number of elements copied. Here, the parameters col specifies the System.Collections.ICollection to copy elements from.
  3. Stack(int initialCapacity): It is used to initialize a new instance of the System.Collections.Stack class that is empty and has the specified initial capacity or the default initial capacity, whichever is greater. Here, the parameter initialCapacity specifies the initial number of elements that the Stack can contain.

Let’s see how to create a stack using the Stack() constructor:
Step1:
As the Stack class belongs to System.Collections namespace, so first, we need to include System.Collections namespace in our program with the help of the “using” keyword as follows:
using System.Collections;

Step2:
Next, we need to create an instance of the Stack class using the Stack() constructor as follows:
Stack stack = new Stack();

How to Add Elements into a Stack Collection in C#?

If you want to add elements to a stack, then you need to use the Push() method of the Stack class.
Push(object obj): The push() method is used to insert an object on top of the Stack. Here, the parameter obj specifies the Object to push onto the Stack. The value can be null.

Example to Understand How to Create a Stack and Add Elements in C#:

For a better understanding of how to create a Stack and how to add elements to a stack in C#, please have a look at the below example.

using System;
using System.Collections;

namespace StackCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a stack collection
             Stack stack = new Stack();

            //Adding item to the stack using the push method
            stack.Push(10);
            stack.Push("Hello");
            stack.Push(3.14f);
            stack.Push(true);
            stack.Push(67.8);
            stack.Push('A');

            //Printing the stack items using foreach loop
            foreach (object item in stack)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand How to Create a Stack and Add Elements in C#

How to Remove Elements from a Non-Generic Stack Collection in C#?

In Stack, you are allowed to remove elements from the top of the stack. The Stack class in C# provides two different methods to remove elements. They are as follows:

  1. Pop(): This method is used to remove and return the object at the top of the Stack. It returns the Object (element) removed from the top of the Stack.
  2. Clear(): This method is used to remove all objects from the Stack.

Let us see an example to understand the Pop and Clear method of Stack in C#. Please have a look at the below example.

using System;
using System.Collections;

namespace StackCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a stack collection
             Stack stack = new Stack();

            //Adding item to the stack using the push method
            stack.Push(10);
            stack.Push("Hello");
            stack.Push(3.14f);
            stack.Push(true);
            stack.Push(67.8);
            stack.Push('A');

            //Printing the stack items using foreach loop
            Console.WriteLine($"All Stack Elements: Count {stack.Count}");
            foreach (var item in stack)
            {
                Console.Write($"{item} ");
            }

            //Removing and Returning an item from the stack using the pop method
            Console.WriteLine($"\n\nDeleted Element: {stack.Pop()}");
            //Printing item after removing the last added item
            Console.WriteLine($"\nAll Stack Elements After Deletion: Count {stack.Count}");
            foreach (var item in stack)
            {
                Console.Write($"{item} ");
            }

            Console.ReadKey();
        }
    }
}
Output:

How to Remove Elements from the Stack in C#

How to get the topmost element of a Stack in C#?

The Stack class in C# provides the following two methods to get the topmost element of the Stack.

  1. Pop(): This method is used to remove and return the object at the top of the Stack. It returns the Object (element) removed from the top of the Stack. If there is no object (or element) present in the stack and if you are trying to remove an item or object from the stack using the pop() method then it will throw an exception i.e. System.InvalidOperationException
  2. Peek(): The peek() method is used to return the object from the top of the Stack without removing it. If there is no object (or element) present in the stack and if you are trying to return an item (object) from the stack using the peek() method then it will throw an exception i.e. System.InvalidOperationException

For a better understanding, please have a look at the below example which shows how to get the topmost element from the stack.

using System;
using System.Collections;

namespace StackCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a stack collection
             Stack stack = new Stack();

            //Adding item to the stack using the push method
            stack.Push(10);
            stack.Push("Hello");
            stack.Push(3.14f);
            stack.Push(true);
            stack.Push(67.8);
            stack.Push('A');

            Console.WriteLine($"Total elements present in stack : {stack.Count}");

            // Fetch the topmost element of stack Using Pop method
            Console.WriteLine($"Topmost element of stack is {stack.Pop()}");

            Console.WriteLine($"Total elements present in stack : {stack.Count}");

            // Fetch the topmost element from Stacj Using Peek method
            Console.WriteLine($"Topmost element of Stack is {stack.Peek()}");

            Console.WriteLine($"Total elements present in stack : {stack.Count}");

            Console.ReadKey();
        }
    }
}
Output:

How to get the topmost element of the Stack in C#

Note: If you want to remove and return the top element from the stack, then use the Pop method and if you only want to return the top element from the stack without removing it, then you need to use the Peek method and this is the only difference between these two methods of Stack class in C#.

How to check whether an element exists or not in the stack in C#?

If you want to check whether an element exists or not in the stack, then you can use the following Contains() method of the Stack class. You can also use this method to search for an element in the given stack.

  1. Contains(object obj): This method is used to determine whether an element is in the Stack. Here, the parameter obj specifies the object or element to locate in the Stack. The value can be null. It returns true if obj is found in the Stack; otherwise, false.

Let us understand this with an example. The following example shows how to use the Contains() method of the non-generic collection Stack class in C#.

using System;
using System.Collections;

namespace StackCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a stack collection
             Stack stack = new Stack();

            //Adding item to the stack using the push method
            stack.Push(10);
            stack.Push("Hello");
            stack.Push(3.14f);
            stack.Push(true);
            stack.Push(67.8);
            stack.Push('A');

            // Checking if the element Hello is present in the Stack or not
            if (stack.Contains("Hello") == true)
            {
                Console.WriteLine("Element Hello is found");
            }
            else
            {
                Console.WriteLine("Element Hello is not found");
            }

            Console.ReadKey();
        }
    }
}

Output: Element Hello is found

Note: The Contains(object obj) method of Stack Class takes O(n) time to check if the element exists in the stack. This should be taken into consideration while using this method.

How to Clone the Non-Generic Stack Collection in C#?

If you want to clone the Non-Generic Stack collection in C#, then you need to use the following Clone() method provided by the Stack Collection Class.

  1. Clone(): This method is used to create and return a shallow copy of a stack object.

For a better understanding, please have a look at the below example.

using System;
using System.Collections;

namespace StackCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a stack collection
            Stack stack = new Stack();

            //Adding item to the stack using the push method
            stack.Push(10);
            stack.Push("Hello");
            stack.Push(3.14f);
            stack.Push(67.8);

            //Printing All Stack Elements using For Each Loop
            Console.WriteLine("Stack Elements:");
            foreach (var item in stack)
            {
                Console.WriteLine(item);
            }

            //Creating a clone queue using Clone method
            Stack cloneStack = (Stack)stack.Clone();
            Console.WriteLine("\nCloned Stack Elements:");
            foreach (var item in cloneStack)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}
Output:

How to Clone the Non-Generic Stack Collection in C#

How to copy a stack to an existing array in C#?

In order to copy a stack to an existing array in C#, we need to use the following CopyTo method of the Non-Generic Stack Collection Class.

  1. CopyTo(Array array, int index): This method is used to copy the Stack elements to an existing one-dimensional Array, starting at the specified array index. Here, the parameter array specifies the one-dimensional array that is the destination of the elements copied from the stack. The Array must have zero-based indexing. The index parameter specifies the zero-based index in the array at which copying begins. If the parameter array is null, then it will throw ArgumentNullException. If the parameter index is less than zero, then it will throw ArgumentOutOfRangeException.

This method works on one-dimensional arrays and does not change the state of the stack. The elements are ordered in the array in the same way as the order of the elements from the start of the stack to the end. Let us see an example for a better understanding.

using System;
using System.Collections;

namespace StackCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a stack collection
            Stack stack = new Stack();

            //Adding item to the stack using the push method
            stack.Push(10);
            stack.Push("Hello");
            stack.Push(3.14f);
            stack.Push(true);
            stack.Push(67.8);

            //Printing All Queue Elements using For Each Loop
            Console.WriteLine("Stack Elements:");
            foreach (var item in stack)
            {
                Console.WriteLine(item);
            }
            //Copying the queue to an object array
            object[] stackCopy = new object[5];
            stack.CopyTo(stackCopy, 0);
            Console.WriteLine("\nStack Copy Array Elements:");
            foreach (var item in stackCopy)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}
Output:

How to copy a stack to an existing array in C#

Properties of Non-Generic Stack Collection Class in C#
  1. Count: It returns the number of elements contained in the Stack.
  2. IsSynchronized: Gets a value indicating whether access to the Stack is synchronized (thread-safe). It returns true if access to the Stack is synchronized (thread-safe); otherwise, false. The default is false.
  3. SyncRoot: Gets an object that can be used to synchronize access to the Stack. It returns an object that can be used to synchronize access to the Stack.
Summary

The following are important points that you need to remember while working with Stack in C#.

  1. 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.
  2. By using the Push() method, we can add elements to a stack.
  3. The Pop() method will remove and return the topmost element from the stack.
  4. The Peek() method will return the last (top-most) inserted element of the stack, and it won’t delete the element from the stack.

In the next article, I am going to discuss the Non-Generic Collection Queue Class in C# with Examples. Here, In this article, I try to explain Non-Generic Collection Stack Class in C# with Examples. I hope this Non-Generic Collection Stack Class in C# article will help you with your needs.

2 thoughts on “Non-Generic Stack in C#”

  1. blank
    Loknadh.Ravineni

    Hi Typing Error under the section Methods of Stack class in C# Here the method name should be Peek() but it was typed as Peep()

Leave a Reply

Your email address will not be published.