Stack Class in C#

In this article we will discuss about what is Stack Class in C# and how it will be implemented.
  • 3162

The System.Collection Class is most important Collection Class which is based on the principle of the LIFO i.e. Last In First Out. In it last inserted item will be the first item to be removed. The Stack is one of the most important Data Structure present in the computer science. The insertion of the item on the stack is called 'Push' and deletion of the item from the stack is called 'Pop'. The System.Collection.Stack class provides the functionality of a Stack in .NET environment. To read the top item of the Stack an operation called Peek is available in the Stack Class.

The following is the code for Stack Class:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

 

namespace ConsoleApplication13

{

    class Program

    {

        static void Main(string[] args)

        {

            Stack st = new Stack();

            st.Push("megha");

            st.Push("meesha");

            st.Push("maggi");

            st.Push("richa");

            st.Push("shruti");

            st.Push("neha");

            Console.WriteLine("Count is:"+st.Count.ToString());

            Console.WriteLine("Top element is:"+st.Peek().ToString());

            while (st.Count > 0)

            {

                Console.WriteLine(st.Pop().ToString());

            }

            Console.WriteLine("Count is:"+st.Count.ToString());

            //foreach(object o in st)

            //{

            //    Console.WriteLine(o.ToString());// to fetch the items

            //}

 

            Console.ReadLine();

 

        }

    }

}

Output:

image5.jpg

Further Readings
 
You may also want to read these related articles.

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.