C# Stack.Peek() technique: Here, we will find out about the Peek() strategy for Stack class in C#.
C# Stack.Peek() technique
Stack.Peek() technique is utilized to get the item at the top from a stack. In Stack.Pop() technique we have talked about that it restores the item from the top and expels the article, yet Stack.Peek() strategy restores an item at the top without expelling it from the stack.
Syntax:
Object Stack.Peek();
Parameters: None
Return value: Object – it restores the topmost 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 article at the top from the stack utilizing Stack.Peek() technique
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