Stack collection in C#

Stack Class

Stack handles last in first out data processing mechanism. Stack class in one of Collection class of .NET Class library. You have to include using System.Collections.Generic; namespace in order to use collection class in your program.

 

Create object of collection class like this

            Stack<Int32> st = new Stack<int>();

And you can call push() or pop() method of collection class in order to insert data and delete data symulteniously.

 

In this below example I have created one object of collection class which is (st). And I have inserted two element in my Stack class. Then I have called st.Pop(); to delete top item of my Stack Collection. Then I am displaying the top most item by calling Peek() function.

 

Console.Write(st.Peek());

And as I have deleted my top most item from stack now my top item is 100.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace BlogProject

{

    class Program

    {

        static void Main(string[] args)

        {

            Stack<Int32> st = new Stack<int>();

            st.Push(100);

            st.Push(200);

            st.Pop();

            Console.Write(st.Peek());

            Console.ReadLine();

        }

    }

}

 Result:- 100

Ebook Download
View all
Learn
View all