Collections C# Book

Stack and Stack are last-in first-out (LIFO) data structures, providing methods to Push and Pop.
The generic Stack has the following methods:

public class Stack : IEnumerable, ICollection, IEnumerable
{
public Stack();
public Stack (IEnumerable collection); // Copies existing elements
public Stack (int capacity); // Lessens auto-resizing
public void Clear();
public bool Contains (T item);
public void CopyTo (T[] array, int arrayIndex);
public int Count { get; }
public Enumerator GetEnumerator(); // To support foreach
public T Peek();
public T Pop();
public void Push (T item);
public T[] ToArray();
public void TrimExcess();
}
The following example demonstrates Stack:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Sample
{
public static void Main()
{
var s = new Stack();
s.Push(1); // Stack = 1
s.Push(2); // Stack = 1,2
s.Push(3); // Stack = 1,2,3
Console.WriteLine(s.Count);
Console.WriteLine(s.Peek());
Console.WriteLine(s.Pop());
Console.WriteLine(s.Pop());
Console.WriteLine(s.Pop());
Console.WriteLine (s.Pop());
}
}
The output:
3
3
3
2
1
Unhandled Exception: System.InvalidOperationException: Stack empty.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resour
ce)
at System.Collections.Generic.Stack`1.Pop()
at Sample.Main() in c:\g\Program.cs:line 19