Home »
C#.Net
Stack.Peek() method with example in C#
C# Stack.Peek() method: Here, we are going to learn about the Peek() method of Stack class in C#.
Submitted by IncludeHelp, on March 28, 2019
C# Stack.Peek() method
Stack.Peek() method is used to get the object at the top from a stack. In Stack.Pop() method we have discussed that it returns the object from the top and removes the object, but Stack.Peek() method returns an object at the top without removing it from the stack.
Syntax:
Object Stack.Peek();
Parameters: None
Return value: Object – it returns the top most object of the stack.
Example:
declare and initialize a stack:
Stack stk = new Stack();
insertting elements:
stk.Push(100);
stk.Push(200);
stk.Push(300);
stk.Push(400);
stk.Push(500);
printig stack's top object/element:
stk.Peek();
Output:
500
C# example to get an object at the top from the stack using Stack.Peek() method
using System;
using System.Text;
using System.Collections;
namespace Test
{
class Program
{
//function to print stack elements
static void printStack(Stack s)
{
foreach (Object obj in s)
{
Console.Write(obj + " ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
//declare and initialize a stack
Stack stk = new Stack();
//insertting elements
stk.Push(100);
stk.Push(200);
stk.Push(300);
stk.Push(400);
stk.Push(500);
//printig stack's top object/element
Console.WriteLine("object at the top is : " + stk.Peek());
//printing stack elements
Console.WriteLine("Stack elements are...");
printStack(stk);
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
object at the top is : 500
Stack elements are...
500 400 300 200 100
Reference: Stack.Peek Method