C Sharp Stack

C# Stack<T>

To push and pop the elements using the concept of the Stack where the elements are arranged in the Last In First Out (LIFO) order, the C# Stack<T> class is used which is found in the System.Collections.Generic namespace. Duplicate elements can also be stored in a C# Stack<T> class.

Example:

using System;  
using System.Collections.Generic;  
 
public class Example  
{  
    public static void Main(string[] args)  
    {  
        Stack countries = new Stack();  
        countries.Push("India");  
        countries.Push("Nepal");  
        countries.Push("Canada");  
        countries.Push("Australia");  
        countries.Push("Japan");  
 
        foreach (string country in countries)  
        {  
            Console.WriteLine(country);  
        }  
 
        Console.WriteLine("Peek element: "+ countries.Peek());  
        Console.WriteLine("Pop: "+ countries.Pop());  
        Console.WriteLine("Peek element after Pop: " + countries.Peek());  
 
    }  
}

Output:

Explanation:

In the above example, we are using the generic Stack<T> class. Here, the Push() method is used to store the elements, the Pop() method is used to remove the elements and the for-each loop is used to iterate the elements.

 

Please Share