// StackTest.cs: Testing generic class Stack. using System; using System.Collections.Generic; class StackTest { // create arrays of doubles and ints private static double[] doubleElements = new double[] { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 }; private static int[] intElements = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; private static Stack doubleStack; // stack stores doubles private static Stack intStack; // stack stores int objects public static void Main(string[] args) { doubleStack = new Stack(5); // stack of doubles intStack = new Stack(10); // stack of ints // push doubles onto doubleStack TestPush("doubleStack", doubleStack, doubleElements); // pop doubles from doubleStack TestPop("doubleStack", doubleStack); // push ints onto intStack TestPush("intStack", intStack, intElements); // pop ints from intStack TestPop("intStack", intStack); } // end Main // *********************************************************** // Generic method TestPush uses type parameter T to represent // the data type stored in the Stack. // *********************************************************** private static void TestPush(string name, Stack stack, IEnumerable elements) { // push elements onto stack try { Console.WriteLine("\nPushing elements onto " + name); // push elements onto stack foreach (var element in elements) { Console.Write("{0} ", element); stack.Push(element); // push onto stack } // end foreach } // end try catch (FullStackException exception) { Console.Error.WriteLine(); Console.Error.WriteLine("Message: " + exception.Message); Console.Error.WriteLine(exception.StackTrace); } // end catch } // end method TestPush // *********************************************************** // Generic method TestPop uses type parameter T to represent // the data type stored in the Stack. // *********************************************************** private static void TestPop(string name, Stack stack) { // push elements onto stack try { Console.WriteLine("\nPopping elements from " + name); T popValue; // store element removed from stack // remove all elements from stack while (true) { popValue = stack.Pop(); // pop from stack Console.Write("{0} ", popValue); } // end while } // end try catch (EmptyStackException exception) { Console.Error.WriteLine(); Console.Error.WriteLine("Message: " + exception.Message); Console.Error.WriteLine(exception.StackTrace); } // end catch } // end TestPop } // end class StackTest