Working With Stack In C#

Introduction

A stack is a LIFO (last in first out) data structure. Think of a stack as a collection of items where anything you insert in a stack will be placed at the top and if you need to remove something, it will be removed from the top. A stack of plates or a book stack are two common examples of a stack.

In this tutorial, we will learn how to use the Stack<> class in C#. We will see how to create a Stack and how to use its Push, Pop, and other methods.

The Stack<T> is a collection that is defined in the System.Collection.Generic namespace where T specified the type of elements in the stack.

Create a Stack

The Stack<> class constructors look like the following.

Constructors

Count items in a stack

The Count property of the Stack class returns the number of elements in a stack. The following code example creates three stacks using different methods and use the Count property to return the number of items in these stacks.

namespace Stack
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack<string> stack1 = new Stack<string>();
            string[] str = {
                "MCA",
                "BCA",
                "BBA",
                "MBA",
                "MTech"
            };
            Stack<string> stack2 = new Stack<string>(str);
            Stack<string> stack3 = new Stack<string>(10);
            
            Console.WriteLine("The elements in stack1 are: " + stack1.Count);
            Console.WriteLine("The elements in stack2 are: " + stack2.Count);
            Console.WriteLine("The elements in stack3 are: " + stack3.Count);
        }
    }
}

The output looks like the following.

Output

Add items to a stack in C#

The Push() method is used to add a (push) element to the stack. The item is added to the top of the stack.

The following code example shows how to use the Push method to add items to a stack.

namespace Stack
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack<string> stack1 = new Stack<string>();
            string[] str = {
                "MCA",
                "BCA",
                "BBA",
                "MBA",
                "MTech"
            };
            Stack<string> stack2 = new Stack<string>(str);
            Stack<string> stack3 = new Stack<string>(10);

            stack1.Push("************");
            stack1.Push("MCA");
            stack1.Push("MBA");
            stack1.Push("BCA");
            stack1.Push("BBA");
            stack1.Push("***********");
            stack1.Push("**Courses**");
            stack1.Push("***********");

            Console.WriteLine("The elements in the stack1 are as:");
            foreach (string s in stack1)
            {
                Console.WriteLine(s);
            }

            Console.WriteLine("The elements in the stack2 are as:");
            foreach (string s in stack2)
            {
                Console.WriteLine(s);
            }

            stack3.Push("one");
            stack3.Push("Two");

            Console.WriteLine("The elements in the stack3 are as:");
            foreach (string s in stack3)
            {
                Console.WriteLine(s);
            }
        }
    }
}

The output looks like the following.

Window

Remove items from a Stack in C#

The Pop() method is used to remove elements from a stack. The Pop() method removes the topmost item from the stack.

The following code example uses the Pop() method three times to remove 3 elements.

namespace Stack
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack<string> stack1 = new Stack<string>();
            stack1.Push("************");
            stack1.Push("MCA");
            stack1.Push("MBA");
            stack1.Push("BCA");
            stack1.Push("BBA");
            stack1.Push("***********");
            stack1.Push("**Courses**");
            stack1.Push("***********");
            
            Console.WriteLine("The elements in the stack1 are as:");
            foreach (string s in stack1)
            {
                Console.WriteLine(s);
            }

            // For removing or popping the elements, pop() method is used
            stack1.Pop();
            stack1.Pop();
            stack1.Pop();

            Console.WriteLine("After removal or popping the elements, the stack is as:");
            // The element that was inserted last is removed first
            foreach (string s in stack1)
            {
                Console.WriteLine(s);
            }
        }
    }
}

The output looks like the following.

System

Get items from a stack in C#

The Peek() method returns the topmost element of a Stack<T> without removing it. The following code snippet reads stack items and displays the content.

namespace Stack {
    class Program {
        static void Main(string[] args) {
            Stack<string> stack1 = new Stack<string>();
            stack1.Push("************");
            stack1.Push("MCA");
            stack1.Push("MBA");
            stack1.Push("BCA");
            stack1.Push("BBA");
            stack1.Push("***********");
            stack1.Push("**Courses**");
            stack1.Push("***********");
            Console.WriteLine("The elements in the stack1 are as:");
            foreach (string s in stack1) {
                Console.WriteLine(s);
            }
            //The first peek element is find by peek() method
            //peek method gives the element that located at the top of the stack
            Console.WriteLine("The peek element is:" + stack1.Peek());
            stack1.Pop();
            Console.WriteLine("The nest peek element is:" + stack1.Peek());
        }
    }
}

The output looks like the following.

CMD

C# Stack Code Example

Here are some code examples of using the Stack class and its methods in C#. The Contain() method determines and returns true if an element is found in a stack. The following example uses the Contain method.

namespace Stack {
    class Program {
        static void Main(string[] args) {
            Stack<string> stack1 = new Stack<string>();
            stack1.Push("************");
            stack1.Push("MCA");
            stack1.Push("MBA");
            stack1.Push("BCA");
            stack1.Push("BBA");
            stack1.Push("***********");
            stack1.Push("**Courses**");
            stack1.Push("***********");
            Console.WriteLine("The elements in the stack1 are as:");
            foreach(string s in stack1) {
                Console.WriteLine(s);
            }
            Console.WriteLine("The element MCA contains in the stack " + stack1.Contains("MCA"));
            Console.WriteLine("The element BCA contains in the stack " + stack1.Contains("BCA"));
            Console.WriteLine("The element MTech contains in the stack " + stack1.Contains("MTech"));
        }
    }
}

The output looks like the following.

Element

The Clear() method of Stack<T> removes all elements from a stack. The following code snippet uses the Clear() method and removes all items in a stack.

namespace Stack {
    class Program {
        static void Main(string[] args) {
            Stack<string> stack1 = new Stack<string>();
            stack1.Push("************");
            stack1.Push("MCA");
            stack1.Push("MBA");
            stack1.Push("BCA");
            stack1.Push("BBA");
            stack1.Push("***********");
            stack1.Push("**Courses**");
            stack1.Push("***********");
            Console.WriteLine("The element in the stack are:" + stack1.Count());
            Console.WriteLine("The elements in the stack1 are as:");
            foreach (string s in stack1) {
                Console.WriteLine(s);
            }
            //clear() method remove/or clear all the elements from the stack
            stack1.Clear();
            Console.WriteLine("After apply the clear method the elements in the stack are:" + stack1.Count());
        }
    }
}

The output looks like the following.

Key

Summary

In this article, I explained the concept of a stack and how to use the Stack<T> class to implement a stack in C#.

Here are recommended articles on collections.

  1. C# Dictionary
  2. C# Queue
  3. C# Stack
  4. C# List
  5. C# Arrays
  6. C# HashTable
  7. C# StringCollection
  8. C# ArrayList
  9. C# HashSet
  10. C# LinkedList


Similar Articles