Stack is a special type of collection object in C#, which stores elements in "Last in First Out" order, known as "LIFO style", c# provides generic and non-generic stack, in this tutorial, you learn how to declare a stack c#, create a stack c#, copy or clone a stack in c# with example
Stack can be non-generic and generic too. non-generic Stack
class comes under
System.Collections
, and generic Stack
class comes under System.Collections.Generic
Stack is a special type of collection in C#, which stores elements in LIFO style(Last In First Out). C# includes a generic and non-generic Stack. Here you will learn about the non-generic stack.
Stack allows duplicate values and also null value, Stack comes under System.Collections namespace
using System.Collections; Stack myStack = new Stack();Initializes a new instance of the Stack class (generic)
using System.Collections.Generic; Stack<string> s = new Stack<string>();
Returns the top item from the stack.
Removes and returns items from the top of the stack.
Checks whether an item exists in the stack or not
Inserts an item at the top of the stack.
Removes all items from the stack.
Push method allows adding object in stack object, so in example below we have created a new instance of stack object, and then added different type of values.
using System.Collections; Stack myStack = new Stack(); myStack.Push(1); myStack.Push(1.10); myStack.Push("this is a string"); myStack.Push(DateTime.Now); myStack.Push(null);
As you can see in above code we have created a stack object called “myStack”, then added few values using push method, now we retrieve those values by looping throw the stack collection object.
foreach (var itm in myStack) { Console.Write(itm); }
Peek method is for retrieving value from stack object, for example, now we want to read the value from above stack collection object "myStack".
Console.WriteLine(myStack.Peek());
The Pop()
method removes and returns the value that was added last to the Stack.
using System.Collections; Stack popStack = new Stack(); popStack.Push(1); popStack.Push(2); popStack.Push(3); popStack.Push(4); Console.Write("Total elements in Stack: {0}", popStack.Count); while (myStack.Count > 0) Console.WriteLine(popStack.Pop()); Console.Write("Total elements in Stack: {0}", popStack.Count);
After executing the above code, the result would be
Total elements in Stack: 4 4 3 2 1 Total elements in Stack: 0
Stack and Queue are both collection objects, they come under System.Collection
namespace,
but there are some differences
You should also look at others C# Data Structures Fundamental.