Stackstack = new Stack (); stack.Push("apple"); stack.Push("banana"); stack.Push("orange"); string top = stack.Peek(); // returns "orange"
StackThis example creates a stack of integers and pushes two numbers onto it. It then uses the Peek method to inspect the top of the stack and store the result in an integer variable. It then removes the top item with the Pop method and uses Peek again to inspect the new top of the stack. The csharp System.Collections Stack Peek method is included in the standard .NET library.stack = new Stack (); stack.Push(5); stack.Push(6); int num1 = stack.Peek(); // returns 6 stack.Pop(); int num2 = stack.Peek(); // returns 5