Queue.Count Property in C#


The Queue.Count property in C# is used to get the number of elements contained in the Queue.

Syntax

The syntax is as follows −

public virtual int Count { get; }

Example

Let us now see an example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<int> queue = new Queue<int>();
      queue.Enqueue(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      queue.Enqueue(400);
      queue.Enqueue(500);
      queue.Enqueue(600);
      queue.Enqueue(700);
      queue.Enqueue(800);
      queue.Enqueue(900);
      queue.Enqueue(1000);
      Console.WriteLine("Queue...");
      foreach(int i in queue) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Count of elements in the Queue = "+queue.Count);
      queue.Clear();
      Console.WriteLine("Count of elements in the Queue [Updated] = "+queue.Count);
   }
}

Output

This will produce the following output −

Queue...
100
200
300
400
500
600
700
800
900
1000
Count of elements in the Queue = 10
Count of elements in the Queue [Updated] = 0

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<int> queue = new Queue<int>();
      queue.Enqueue(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      Console.WriteLine("Queue...");
      foreach(int i in queue) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Count of elements in the Queue = "+queue.Count);
      queue.Enqueue(800);
      queue.Enqueue(900);
      queue.Enqueue(1000);
      Console.WriteLine("Count of elements in the Queue [Updated] = "+queue.Count);
      queue.Clear();
      Console.WriteLine("Count of elements in the Queue [Updated] = "+queue.Count);
   }
}

Output

This will produce the following output −

Queue...
100
200
300
Count of elements in the Queue = 3
Count of elements in the Queue [Updated] = 6
Count of elements in the Queue [Updated] = 0

Updated on: 04-Dec-2019

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements