Stack.ToArray() Method in C#

This method(comes under System.Collections namespace) is used to copy a Stack to a new array. The elements are copied onto the array in last-in-first-out (LIFO) order, similar to the order of the elements returned by a succession of calls to Pop. This method is an O(n) operation, where n is Count.

Syntax:

public virtual object[] ToArray ();

Return Type: This method returns a new array of type System.Object containing copies of the elements of the Stack.

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

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to illustrate the
// Stack.ToArray() Method
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push("Geeks");
        myStack.Push("Geeks Classes");
        myStack.Push("Noida");
        myStack.Push("Data Structures");
        myStack.Push("GeeksforGeeks");
  
        // Converting the Stack into array
        Object[] arr = myStack.ToArray();
  
        // Displaying the elements in array
        foreach(Object str in arr)
        {
            Console.WriteLine(str);
        }
    }
}

chevron_right


Output:

GeeksforGeeks
Data Structures
Noida
Geeks Classes
Geeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to illustrate the
// Stack.ToArray() Method
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push(2);
        myStack.Push(3);
        myStack.Push(4);
        myStack.Push(5);
        myStack.Push(6);
  
        // Converting the Stack into array
        Object[] arr = myStack.ToArray();
  
        // Displaying the elements in array
        foreach(Object i in arr)
        {
            Console.WriteLine(i);
        }
    }
}

chevron_right


Output:

6
5
4
3
2

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.