System.Collections.Stack.Peek C# (CSharp) Method

Peek() public method

public Peek ( ) : Object
return Object
        public virtual Object Peek()
        {
            if (_size == 0)
                throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
            Contract.EndContractBlock();
            return _array[_size - 1];
        }

Same methods

Stack::Peek ( ) : object

Usage Example

        static void Main(string[] args)
        {
            // Stack - A LIFO collection

            Stack<string> stack = new Stack<string>();

            stack.Push("A");  // Push adds to the stack
            stack.Push("B");
            stack.Push("C");
            stack.Push("D");

            Console.WriteLine(stack.Peek()); // D - Peek returns the last added value without removing it

            Console.WriteLine(stack.Pop()); // D - Pop returna the last added value and removes it

            Console.WriteLine(stack.Peek());  // C

            // Queue - A FIFO collection

            Queue<string> queue = new Queue<string>();

            queue.Enqueue("a"); // Enqueue adds to the queue
            queue.Enqueue("b");
            queue.Enqueue("c");
            queue.Enqueue("d");

            Console.WriteLine(queue.Peek()); // a - Peek returns the beginning value without removing it

            Console.WriteLine(queue.Dequeue()); // a - Dequeue returns the beginning value and removes it

            Console.WriteLine(queue.Peek()); // b

            //--
            Console.ReadKey();
        }
All Usage Examples Of System.Collections.Stack::Peek