C# Stack - Peek() Method



The C# stack Peek() method is used to return the object at the top of the stack without removing it.

This method is similar to the Pop method, but Peek does not modify the stack.

Syntax

Following is the syntax of the C# stack Peek() method −

public virtual object? Peek();

Parameters

This method does not accepts any parameters.

Return value

This method returns an object from the top of the stack.

Example 1: Return Top element from Stack

Following is the basic example of the Peek() method to return the top element from the stack −

using System;
using System.Collections.Generic;

class Example1 {
   static void Main() {
      Stack<int> numbers = new Stack<int>();
      // Pushing elements onto the stack
      numbers.Push(10);
      numbers.Push(20);
      numbers.Push(30);
      
      Console.WriteLine("Peek Element: " + numbers.Peek());
   }
}

Output

Following is the output −

Peek Element: 30

Example 2: Retrieving Top Element From Stack<string>

Let's see another example of the Peek() method. Here, we retrieve the top element form the stack<string> −

using System;
using System.Collections.Generic;

class Example1 {
   static void Main() {
      Stack<string> stacks = new Stack<string>();
      // Pushing elements onto the stack
      stacks.Push("Hello");
      stacks.Push("This");
      stacks.Push("is");
      stacks.Push("tutorialspoint");
      
      Console.WriteLine("Peek Element: " + stacks.Peek());
   }
}

Output

Following is the output −

Peek Element: tutorialspoint

Example 3: Handling Empty Stack Scenario

The below example uses the Peek() method to retrieve the top element if the stack is not empty −

using System;
using System.Collections.Generic;

class Example1 {
   static void Main() {
      Stack<string> stacks = new Stack<string>();
      // Pushing elements onto the stack
      stacks.Push("Hello");
      stacks.Push("This");
      stacks.Push("is");
      stacks.Push("tutorialspoint");
      
      if (stacks.Count > 0) {
        Console.WriteLine("Top Element: " + stacks.Peek());
      }      
      else {
        Console.WriteLine("Stack is empty, cannot peek.");
      }
   }
}

Output

Following is the output −

Top Element: tutorialspoint
csharp_stack.htm
Advertisements