C Sharp Stack

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# Stack<T>

C# Stack class is used to push and pop elements. It uses the concept of Stack that arranges elements in LIFO (Last In First Out) order. It can have duplicate elements. It is found in System.Collections.Generic namespace.

C# Stack<T> example

Let's see an example of generic Stack class that stores elements using Push() method, removes elements using Pop() method and iterates elements using for-each loop.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class StackExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         Stack<string> names = new Stack<string>();  
  9.         names.Push("Sonoo");  
  10.         names.Push("Peter");  
  11.         names.Push("James");  
  12.         names.Push("Ratan");  
  13.         names.Push("Irfan");  
  14.   
  15.         foreach (string name in names)  
  16.         {  
  17.             Console.WriteLine(name);  
  18.         }  
  19.   
  20.         Console.WriteLine("Peek element: "+names.Peek());  
  21.         Console.WriteLine("Pop: "+ names.Pop());  
  22.         Console.WriteLine("After Pop, Peek element: " + names.Peek());  
  23.   
  24.     }  
  25. }  

Output:

Sonoo
Peter
James
Ratan
Irfan
Peek element: Irfan
Pop: Irfan
After Pop, Peek element: Ratan