Author : MD TAREQ HASSAN | Updated : 2021/03/22

Creating Stack

// creating stack
var items = new Stack<string>();

//  pushing
items.Push("foo");
items.Push("bar");
items.Push("bax");

// creating from array
var items = new Stack<string>(new string[] { "foo", "bar", "bax" });  

Links

Stack methods

// count
var count = items.Count;   // 3

// peek
var bax = items.Peek();   // items.Count => 3

// pop
var bax = items.Pop();    //  items.Count => 2

// Contains
var doesContainFoo = items.Contains("foo");  // true

// remove all items
items.Clear();      //  items.Count => 0

Char Array to Stack

var chars = new char[] { 'a', 'x', 'b', 'y', 'c', 'z'};
var charStack = new Stack<char>(chars);
foreach(var ch in charStack){ // prints chars in reverse order
	Console.WriteLine(ch);
}

Stack to Char Array

var charStack = new Stack<char>( new char[] { 'a', 'x', 'b', 'y', 'c', 'z'});
var chars = charStack.ToArray();  // if you print chars, compiler will automatically call chars.ToString() and therefore will be printed as "zcybxa", but actually char[]

// CopyTo
var charStack = new Stack<char>( new char[] { 'a', 'x', 'b', 'y', 'c', 'z'});
var chars = new char[charStack.Count];
charStack.CopyTo(chars, arrayIndex: 0);

String to Stack

var str = "ax by cz";
var wordStack = new Stack<string>(str.Split(" "));

Stack to String

var wordStack = new Stack<string>(new string[]{ "ax", "by", "cz" }) ;
var str = String.Join(" ",  wordStack);
Console.WriteLine(str);

Array to Stack

var intArray = new int[] { 1, 3, 5, 7 };
var intStack = new Stack<int>(intArray) ;
foreach(var item in intStack){
	Console.WriteLine(item);
}

Stack to Array

var intSatck = new Stack<int>(new int[] { 1, 3, 5, 7 }) ;
var intArray = intSatck.ToArray();
foreach(var item in intArray){
	Console.WriteLine(item);
}

List to Stack

var list = new List<int>() { 1, 3, 5, 7};
var intStack = new Stack<int>(list) ;
foreach(var item in intStack){
	Console.WriteLine(item);
}

// poping in same order
list.Reverse();
var intStack = new Stack<int>(list) ;
foreach(var item in intStack){
	Console.WriteLine(item);
}

Stack to List

var intStack = new Stack<int>(new List<int>() { 1, 3, 5, 7}) ;
var list = new List<int>(intStack);

// LINK
var list = intStack.ToList();