Queue.CopyTo() method with example in C#

C# Queue.CopyTo() strategy: Here, we will find out about the CopyTo() technique for Queue class in C#.

C# Queue.CopyTo() strategy

Queue.CopyTo() strategy is utilized to duplicate the Queue components/items to a current cluster from determined record.

Syntax:

    void Queue.CopyTo(Array, Int32);

Parameters: Array – Targeted array_name in which we need to duplicate the line components/objects, Int32 – is a list in focused array_name from where line components/objects are replicated.

Return value: void – it returns nothing.

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);
    
    using CopyTo(), copying queue elements to the array:
    que.CopyTo(arr, 3); //will copy from 3rd index in array

    Output:
    arr: 0 0 0 100 200 300 400 500 0 0 0 0 0 0 0 0 0 0 0 0

C# example to duplicate line components/articles to a cluster utilizing Queue.CopyTo() strategy

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();

            //an array declaration for 20 elements
            int[] arr = new int[20];

            //insertting elements
            que.Enqueue(100);
            que.Enqueue(200);
            que.Enqueue(300);
            que.Enqueue(400);
            que.Enqueue(500);

            //printing Queue elements
            Console.WriteLine("Queue elements...");
            printQueue(que);

            //printing array 
            Console.WriteLine("Array elements before CopyTo()...");
            foreach (int item in arr)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();

            //using CopyTo(), copying Queue elements to the array
            que.CopyTo(arr, 3);

            //printing array 
            Console.WriteLine("Array elements after CopyTo()...");
            foreach (int item in arr)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();          

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

Queue elements...
100 200 300 400 500
Array elements before CopyTo()...
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Array elements after CopyTo()...
0 0 0 100 200 300 400 500 0 0 0 0 0 0 0 0 0 0 0 0

Leave a Comment

error: Alert: Content is protected!!