C# | Copy the Stack to an Array (original) (raw)

Last Updated : 01 Feb, 2019

Stack.CopyTo(T[], Int32) Method is used to copy the Stack to an existing 1-D Array which starts from the specified array index.Properties:

Syntax:

public void CopyTo (T[] array, int arrayIndex);

Parameters:

array: The one-dimensional Array that is the destination of the elements copied from Stack<**T**>. The Array must have zero-based indexing.arrayIndex: The zero-based index in array at which copying begins.

Exceptions:

Below given are some examples to understand the implementation in a better way:Example 1:

CSHARP `

// C# code to Copy the Stack to an Array using System; using System.Collections.Generic;

class GFG {

// Driver code
public static void Main()
{

    // Creating a Stack of strings
    Stack<string> myStack = new Stack<string>();

    // Inserting the elements into the Stack
    myStack.Push("Geeks");
    myStack.Push("Geeks Classes");
    myStack.Push("Noida");
    myStack.Push("Data Structures");
    myStack.Push("GeeksforGeeks");

    // Creating a string array arr
    string[] arr = new string[myStack.Count];

    // Copying the elements of stack into array arr
    myStack.CopyTo(arr, 0);

    // Displaying the elements in array arr
    foreach(string str in arr)
    {
        Console.WriteLine(str);
    }
}

}

`

Output:

GeeksforGeeks Data Structures Noida Geeks Classes Geeks

Example 2:

CSHARP `

// C# code to Copy the Stack to an Array using System; using System.Collections.Generic;

class GFG {

// Driver code
public static void Main()
{

    // Creating a Stack of Integers
    Stack<int> myStack = new Stack<int>();

    // Inserting the elements into the Stack
    myStack.Push(2);
    myStack.Push(3);
    myStack.Push(4);
    myStack.Push(5);
    myStack.Push(6);

    // Creating an Integer array arr
    int[] arr = new int[myStack.Count];

    // Copying the elements of stack into array arr
    myStack.CopyTo(arr, 0);

    // Displaying the elements in array arr
    foreach(int i in arr)
    {
        Console.WriteLine(i);
    }
}

}

`

Reference:

Similar Reads