Stack.ToArray() Method in C#
Last Updated :
04 Feb, 2019
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:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Stack myStack = new Stack();
myStack.Push( "Geeks" );
myStack.Push( "Geeks Classes" );
myStack.Push( "Noida" );
myStack.Push( "Data Structures" );
myStack.Push( "GeeksforGeeks" );
Object[] arr = myStack.ToArray();
foreach (Object str in arr)
{
Console.WriteLine(str);
}
}
}
|
Output:
GeeksforGeeks
Data Structures
Noida
Geeks Classes
Geeks
Example 2:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Stack myStack = new Stack();
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
myStack.Push(5);
myStack.Push(6);
Object[] arr = myStack.ToArray();
foreach (Object i in arr)
{
Console.WriteLine(i);
}
}
}
|
Reference:
Share your thoughts in the comments
Please Login to comment...