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