HOME RESOURCES PLACEMENTS CONTACT FEEDBACK SUBSCRIBE
QUICK LINKS .NET Articles
.NET Training Tutorial
HR Interview Questions
.NET Interview Questions
SQL Interview Questions
JAVA Interview Questions

Stack Collection Type
A stack class is like a stack of books one over the other. If you add another book, the book will be on top of the stack. When you need to remove a book from the stack, you will have to remove the the last book first.

The Stack class is a last-in-first-out(LIFO) collection class that is present in System.Collections namespace.

Use Queue if you need to access the information in the same order that it is stored in the collection. Use Stack if you need to access the information in reverse order.
Example
In the example below
  • Push() method inserts an object at the top of the Stack.
  • Pop() method removes and returns the object at the top of the Stack.
  • Peek() method returns the object at the top of the Stack without removing it.
  • Count property determines the number of elements contained in the Stack.
  • Clear() method removes all the items from the Stack.

using System;

using System.Collections;

class StackDemo

{

    public static void Main()

    {

        //Create an instance of Stack

        Stack S = new Stack();

        //Add elements to the Stack using Push() Method

        S.Push("Prasad");

        S.Push("Giri");

        S.Push("Ravi");

        //Pop() removes and returns the object at the top of the Stack

        Console.WriteLine(S.Pop());

        //Count determines the number of elements contained in the Stack

        //Count will be 2 as we removed the top object from the Stack

        Console.WriteLine("Count = " + S.Count);

        //Peek() method returns the object at the top of the Stack without

        //removing from the Stack

        Console.WriteLine(S.Peek());

        //The count will still be 2 as the peek() method will not remove the object

        //from the Stack

        Console.WriteLine("Count = " + S.Count);

        //Remove all the items from the Stack using Clear() method

        S.Clear();

    }

}

Other related articles

Njoy Programming
   ByPrasad Cherukuri