CSharp - Stack<T> and Stack

Introduction

Stack<T> and Stack are last-in, first-out (LIFO) data structures, providing methods to Push and Pop.

Peek method returns the element at the head of the stack without removing it.

Count property tells the element count.

ToArray method exports the data for random access:

The following example demonstrates Stack<int>:

Demo

using System;
using System.Collections.Generic;
class MainClass//  www.  j  a va 2 s.  c  o  m
{
   public static void Main(string[] args)
   {
         var s = new Stack<int>();
         s.Push (1);                      //            Stack = 1
         s.Push (2);                      //            Stack = 1,2
         s.Push (3);                      //            Stack = 1,2,3
         Console.WriteLine (s.Count);     // Prints 3
         Console.WriteLine (s.Peek());    // Prints 3,  Stack = 1,2,3
         Console.WriteLine (s.Pop());     // Prints 3,  Stack = 1,2
         Console.WriteLine (s.Pop());     // Prints 2,  Stack = 1
         Console.WriteLine (s.Pop());     // Prints 1,  Stack = <empty>
         Console.WriteLine (s.Pop());     // throws exception
   }
}

Result