 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Copy the Stack to an Array in C#
To copy the stack to an array, the code is as follows −
Example
using System; using System.Collections.Generic; public class Demo {    public static void Main(){       Stack<int> stack = new Stack<int>();       stack.Push(10);       stack.Push(20);       stack.Push(30);       stack.Push(40);       stack.Push(50);       stack.Push(60);       stack.Push(70);       stack.Push(80);       stack.Push(90);       stack.Push(100);       Console.WriteLine("Displaying the stack...");       foreach(int val in stack){          Console.WriteLine(val);       }       int[] intArr = new int[stack.Count];       stack.CopyTo(intArr, 0);       Console.WriteLine("Displaying the array...");       foreach(int val in intArr){          Console.WriteLine(val);       }    } }  Output
This will produce the following output −
Displaying the stack... 100 90 80 70 60 50 40 30 20 10 Displaying the array... 100 90 80 70 60 50 40 30 20 10
Example
Let us now see another example −
using System; using System.Collections.Generic; public class Demo {    public static void Main(){       Stack<int> stack = new Stack<int>();       stack.Push(10);       stack.Push(20);       stack.Push(30);       stack.Push(40);       stack.Push(50);       Console.WriteLine("Displaying the stack...");       foreach(int val in stack){          Console.WriteLine(val);       }       int[] intArr = new int[10];       stack.CopyTo(intArr, 2);       Console.WriteLine("Displaying the array...");       foreach(int val in intArr){          Console.WriteLine(val);       }    } }  Output
This will produce the following output −
Displaying the stack... 50 40 30 20 10 Displaying the array... 0 0 50 40 30 20 10 0 0 0
Advertisements
 