Stack class in C#

  • Stack class object stores elements in Last In First Out(LIFO) manner, i.e. Element that gets added last into the stack will get removed first from the stack.
  • Element gets added from and removed from same end.
  • Use stack when you want to access element in the reverse order that they are stored in the collection. 
  • Use stack if you want to discard the element as soon as you retrieve it.
See below example of using stack with its main functions.

+
Code
using System;
using System.Collections;
 
namespace Stack_Collection
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack stkEmp = new Stack();
 
            Employee emp1 = new Employee() { empId = 111, empName = "Sam" };
            Employee emp2 = new Employee() { empId = 112, empName = "Jane" };
            Employee emp3 = new Employee() { empId = 113, empName = "Sachin" };
            Employee emp4 = new Employee() { empId = 114, empName = "Jack" };
 
            stkEmp.Push(emp1);
            stkEmp.Push(emp2);
            stkEmp.Push(emp3);
            stkEmp.Push(emp4);
 
            Console.WriteLine("Retrieving elements from Stack\n");
 
            while (stkEmp.Count > 0)
            {
                Console.WriteLine("Employee Id: {0} information", ((Employee)stkEmp.Peek()).empId);
                Employee emp = (Employee)stkEmp.Pop();
                Console.WriteLine("Emplopyee Id : {0} \t Employee Name : {1}", emp.empId, emp.empName);
                Console.WriteLine("Elements in Stack are:{0}\n", stkEmp.Count);
            }
 
            Console.ReadLine();
        }
 
    }
 
    public class Employee
    {
        public int empId { getset; }
        public string empName { getset; }
    }
}

In the above code sample, We have created a class called Employee with 2 Properties empId, empName.
We have created a Stack class object stkEmp and storing few Employee objects in it. Below are the main functions of Stack that we used in our above code.

Push: Add the element at the begining of Stack.
Pop : Retrieve and remove the top element from the Stack.
Peek : Peek function retrieves top element from the stack but it does not remove it.

Below is the output of above program



If you see the output above, The element that gets added last in stack will get retrieved and removed first when we use Pop method of stack. 

No comments :