Stack in C#

Stack in C# with Examples

In this article, I am going to discuss the Stack in C# with examples. Please read our previous article before proceeding to this article where we discussed Hashtable in C# with examples. 

What is Stack in C#?

The Stack in C# is a non-generic collection class which 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 as pushing an item. Similarly when we remove an item from the stack then it is called as 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 on 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.

Note: The Stack Collection in C# allows both null and duplicate values.

Methods of Stack class in C#:

Push(): The push() method is used to Inserts an object on top of the Stack.

Syntax: void Stack.Push(Object obj)

Pop(): The pop() method is used to Remove and return the object at 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

Syntax: Object stack.pop()

Peep(): The peep() 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 peep() method then it will throw an exception i.e. System.InvalidOperationException

Syntax: object Stack.Peep()

Example: Let us understand the above methods of Stack class using an example.
using System;
using System.Collections;

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

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

            //Printing the stack items using foreach loop
            foreach (object obj in s)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();

            //Removing annd returning an item from the stack
            //using the pop method
            Console.WriteLine(s.Pop());
            Console.WriteLine();

            //Printing item after removing the last added item
            foreach (object obj in s)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();

            //Returning the last item from the stack without removing it
            //by using the peek method
            Console.WriteLine(s.Peek());
            Console.WriteLine();

            //Printing the items after using the Peek method
            foreach (object obj in s)
            {
                Console.Write(obj + " ");
            }

            Console.ReadKey();
        }
    }
}
OUTPUT:

Stack in C#

Let us discuss some other methods and properties of Stack Class:

Count: The Count property of the Stack class is used to return the number of elements present in the Stack.
Syntax: Stack.Count

Contains(): The Contains() method of the Stack class is used to Check whether an element is present in the Stack or not. If it presents, then it will return true else it will return false.
Syntax: Stack.Contains(element)

Clear(): The Clear() method of the Stack class is used to remove all the elements from the stack.
Syntax: Stack.Clear()

Example: Let us see an example for a better understanding of the above methods and properties
using System;
using System.Collections;

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

            //Adding item to the stack using the push method
            s.Push(20);
            s.Push("hi");
            s.Push(3.14f);
            s.Push(true);
            s.Push(12.3);
            s.Push('P');

            //Printing the stack items using foreach loop
            foreach (object obj in s)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();

            //Using Count property to get the number of items
            //present in the collection
            Console.WriteLine($"No of Elements in the Collection : {s.Count}");
            Console.WriteLine();

            //Using the Contains method to check whether an item is present or not
            Console.WriteLine($"Is the value hi present in the collection : {s.Contains("hi")}");
            Console.WriteLine();

            //Removing all the items from the collection using Clear() method
            s.Clear();
            Console.WriteLine($"No of Elements in the Collection after Clear() method : {s.Count}");
            
            Console.ReadKey();
        }
    }
}

Output:

Stack in C#

In the next article, I am going to discuss the Queue non-generic collection in C# with examples. 

SUMMARY:

In this article, I try to explain Stack in C# with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *