Home »
C#.Net
Queue.CopyTo() method with example in C#
C# Queue.CopyTo() method: Here, we are going to learn about the CopyTo() method of Queue class in C#.
Submitted by IncludeHelp, on March 30, 2019
C# Queue.CopyTo() method
Queue.CopyTo() method is used to copy the Queue elements/objects to an existing array from specified index.
Syntax:
void Queue.CopyTo(Array, Int32);
Parameters: Array – Targeted array_name in which we have to copy the queue elements/objects, Int32 – is an index in targeted array_name from where queue elements/objects are copied.
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 copy queue elements/objects to an array using Queue.CopyTo() 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();
//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
Reference: Queue.CopyTo(Array, Int32) Method