class Program { // an ordinary function that is called by value public static void PrintStack(Stack s) { Stack r = new Stack(); // pop and print while (s.Count != 0) { T elem = s.Pop(); Console.Out.WriteLine(elem); r.Push(elem); } // put it all back while (r.Count != 0) { s.Push(r.Pop()); } } // a common programming mistake: s is a copy of the // one the function was called with, so s = r just // reassigns s _local to this function_, so the change // does not persist public static void PrintStack2(Stack s) { Stack r = new Stack(); // pop and print while (s.Count != 0) { T elem = s.Pop(); Console.Out.WriteLine(elem); r.Push(elem); } s = r; } // This version actually _does_ work, though, because // C# lets you use call-by-reference if you want // (when using the ref keyword). public static void PrintStack3(ref Stack s) { Stack r = new Stack(); // pop and print while (s.Count != 0) { T elem = s.Pop(); Console.Out.WriteLine(elem); r.Push(elem); } s = r; } public static void Main(string[] args) { Stack s = new Stack(); s.Push("class"); s.Push("dear"); s.Push("hello"); // works great Console.Out.WriteLine("\nPrintStack (call-by-value semantics):"); PrintStack(s); // does not work great // in fact, PrintStack2 empties // the stack. yuck. Console.Out.WriteLine("\nPrintStack 2 (call-by-value; broken though):"); PrintStack2(s); Console.Out.WriteLine("Nothing printed here ->"); PrintStack(s); Console.Out.WriteLine("<- Nothing printed here"); // I need to restore the stack because // PrintStack2 mangled it s.Push("class"); s.Push("dear"); s.Push("hello"); // but this does work // note that I have to 'opt in' // to call-by-reference both in the // function definition AND in the // function call Console.Out.WriteLine("\nPrintStack 3 (call-by-reference):"); PrintStack3(ref s); PrintStack(s); } }