Convert Stack to array in C#


To convert stack to the array, the code is as follows −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Stack<string> stack = new Stack<string>();
      stack.Push("AB");
      stack.Push("CD");
      stack.Push("FG");
      stack.Push("KL");
      Console.WriteLine("Array...");
      foreach(string i in stack){
         Console.WriteLine(i);
      }
      string[] strArr = stack.ToArray();
      Console.WriteLine("Convert Stack to Array...");
      foreach(string i in strArr){
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

Array...
KL
FG
CD
AB
Convert Stack to Array...
KL
FG
CD
AB

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Stack<int> stack = new Stack<int>();
      stack.Push(250);
      stack.Push(500);
      stack.Push(750);
      stack.Push(1000);
      stack.Push(1200);
      stack.Push(1500);
      Console.WriteLine("Array...");
      foreach(int i in stack){
         Console.WriteLine(i);
      }
      int[] intArr = stack.ToArray();
      Console.WriteLine("Convert Stack to Array...");
      foreach(int i in intArr){
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

Array...
1500
1200
1000
750
500
250
Convert Stack to Array...
1500
1200
1000
750
500
250

Updated on: 06-Dec-2019

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements