Stack.CopyTo() method with example in C#

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

C# Stack.CopyTo() strategy

Stack.CopyTo() strategy is utilized to duplicate the stack components/articles to a current cluster from the given list.

Syntax:

    void Stack.CopyTo(Array, Int32);

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

Return value: void – it returns nothing.

Example:

    declare and initialize a stack:
    Stack stk = new Stack();
    
    an array declaration for 20 elements:
    int[] arr = new int[20];

    insertting elements:
    stk.Push(100);
    stk.Push(200);
    stk.Push(300);
    stk.Push(400);
    stk.Push(500);

    using CopyTo(), copying stack elements to the array:
    stk.CopyTo(arr, 3); //will copy from 3rd index in array
    
    Output:
    arr: 0 0 0 500 400 300 200 100 0 0 0 0 0 0 0 0 0 0 0 0

C# example to duplicate stack components/articles to an exhibit utilizing Stack.CopyTo() technique

using System;
using System.Text;
using System.Collections;

namespace Test
{
    class Program
    {
        //function to print stack elements
        static void printStack(Stack s)
        {
            foreach (Object obj in s)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            //declare and initialize a stack
            Stack stk = new Stack();

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

            //insertting elements
            stk.Push(100);
            stk.Push(200);
            stk.Push(300);
            stk.Push(400);
            stk.Push(500);

            //printing stack elements
            Console.WriteLine("Stack elements are...");
            printStack(stk);

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

            //using CopyTo(), copying stack elements to the array
            stk.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

Stack elements are...
500 400 300 200 100
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 500 400 300 200 100 0 0 0 0 0 0 0 0 0 0 0 0

Leave a Comment

error: Alert: Content is protected!!