Stack Implementation in C#


It represent a LIFO (Last In First Out) collection of object. Stack is used when you need last-in, first-out access of object that means accessing the last inserting item. Stack basically consist of two operation Push and Pop. When you insert an element in stack , it is called pushing the item and when you extract the item from stack , it is called popping the item. Both Push and Pop operation take place at the top of stack. To use stack data type in c# first you should need to use System.Collections namespace.

Properties of stack: 

  1. Count: Count return the number of elements present in the stack.

Method of stack:

  1. public virtual void Push(object obj); It simply insert an object at the top of stack.

  2. public virtual object Pop(object obj); It simply remove and return the object from top of the stack.

  3. public virtual void Clear(); It clears the stack means this method remove all the element from stack.

  4. public virtual object Peek(); This method return the object from top of the stack (without Removing).

  5. public virtual object[] ToArray(); This method copy the stack into a object array.

  6. pjublic virtual bool Contains(object obj); This method is used to check whether an element is exist in the stack. It return True when item exist in the stack otherwise it return False.

Here is the example:

  1. using System;  
  2. using System.Collections;  
  3. namespace Test_Cdac   
  4. {  
  5.     class Program   
  6.     {  
  7.         static void Main(string[] args)   
  8.         {  
  9.             Stack st = new Stack();  
  10.             st.Push("Pankaj");  
  11.             st.Push(1);  
  12.             st.Push(10.5);  
  13.             st.Push(true);  
  14.             st.Push('A');  
  15.             Console.WriteLine("Count : {0}", st.Count);  
  16.             Console.WriteLine();  
  17.             Console.WriteLine("Element in stack : ");  
  18.             foreach(object obj in st)  
  19.             Console.WriteLine(obj);  
  20.             Console.WriteLine();  
  21.             Console.WriteLine("Top most element of stack : {0}", st.Peek());  
  22.             Console.WriteLine();  
  23.             object TopElement = st.Pop();  
  24.             Console.WriteLine("Removing Top element of Stack = {0}\nNow Top element of stack = {1}\n", TopElement, st.Peek());  
  25.             if (st.Contains("Pankaj")) Console.WriteLine("Pankaj Found");  
  26.             else Console.WriteLine("Pankaj Not found");  
  27.             Object[] ob = st.ToArray();  
  28.             Console.WriteLine();  
  29.             foreach(object obj in ob)  
  30.             Console.WriteLine(obj);  
  31.             st.Clear();  
  32.             Console.WriteLine();  
  33.             Console.WriteLine("Count : {0}", st.Count);  
  34.             Console.ReadKey();  
  35.         }  
  36.     }  
  37. }