Queue.Peek Method in C#


The Queue.Peek() method in C# is used to return the object at the beginning of the Queue without removing it.

Syntax

The syntax is as follows −

public virtual object Peek ();

Example

Let us now see an example −

 Live Demo

using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Queue queue = new Queue();
      queue.Enqueue("AB");
      queue.Enqueue("BC");
      queue.Enqueue("CD");
      queue.Enqueue("DE");
      queue.Enqueue("EF");
      queue.Enqueue("FG");
      queue.Enqueue("GH");
      queue.Enqueue("HI");
      Console.WriteLine("Queue...");
      IEnumerator demoEnum = queue.GetEnumerator();
      while (demoEnum.MoveNext()) {
         Console.WriteLine(demoEnum.Current);
      }
      Console.WriteLine("Queue element at the beginning = "+queue.Peek());
      Console.WriteLine("Is Queue synchronized? = "+queue.IsSynchronized);
      Queue queue2 = Queue.Synchronized(queue);
      Console.WriteLine("Is Queue synchronized now? = "+queue2.IsSynchronized);
   }
}

Output

This will produce the following output −

Queue...
AB
BC
CD
DE
EF
FG
GH
HI
Queue element at the beginning = AB
Is Queue synchronized? = False
Is Queue synchronized now? = True

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("Gary");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      queue.Enqueue("Mark");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      Console.Write("Count of elements = ");      
      Console.WriteLine(queue.Count);
      Console.WriteLine("Queue element at the beginning = "+queue.Peek());
      Console.WriteLine("Does the queue has element Jack? = "+queue.Contains("Jack"));
      queue.Clear();
      Console.Write("Count of elements (updated) = ");
      Console.WriteLine(queue.Count);
   }
}

Output

This will produce the following output −

Count of elements = 8
Queue element at the beginning = Gary
Does the queue has element Jack? = True
Count of elements (updated) = 0

Updated on: 04-Dec-2019

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements