C# Stack<T> 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.
Let's see an example of generic Stack<T> class that stores elements using Push() method, removes elements using Pop() method and iterates elements using for-each loop.
using System; using System.Collections.Generic; public class StackExample { public static void Main(string[] args) { Stacknames = new Stack (); names.Push("Sonoo"); names.Push("Peter"); names.Push("James"); names.Push("Ratan"); names.Push("Irfan"); foreach (string name in names) { Console.WriteLine(name); } Console.WriteLine("Peek element: "+names.Peek()); Console.WriteLine("Pop: "+ names.Pop()); Console.WriteLine("After Pop, Peek element: " + names.Peek()); } }