Mega Code Archive

 
Categories / C# Book / 03 Collections
 

0358 Generic Stack and non-generic Stack

Stack<T> 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<T> : IEnumerable<T>, ICollection, IEnumerable { public Stack(); public Stack (IEnumerable<T> 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<T> 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<int>: using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Sample { public static void Main() { 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); 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