C# Stack<T>

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.

C# Stack<T> example

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.

snippet
using System;
using System.Collections.Generic;

public class StackExample
{
    public static void Main(string[] args)
    {
        Stack names = 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());

    }
}

Output:

Output
Sonoo Peter James Ratan Irfan Peek element: Irfan Pop: Irfan After Pop, Peek element: Ratan
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents