WebTrainingRoom Online Courses
Learn C# programming Language, Free C# Tutorial for Beginners, C# Development Guide

Stack in C#, LIFO style Collection

What is Stack in C#
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

Important Methods of Stack in C#

Method Description
Peek Returns the top item from the stack.
Pop Removes and returns items from the top of the stack.
Contains Checks whether an item exists in the stack or not
Push Inserts an item at the top of the stack.
Clear Removes all items from the stack.

Stack example in C#

Push example in Stack in C#
Stack myStack = new Stack();
myStack.Push(1);
myStack.Push(1.10);
myStack.Push("this is a string");
myStack.Push(DateTime.Now);
myStack.Push(null);

To retrive item from stack
foreach (var itm in myStack)                
{
Console.Write(itm);
}

Peek example in Stack in C#
Console.WriteLine(myStack.Peek());

Pop example in Stack in C#
The Pop() method removes and returns the value that was added last to the Stack.
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

 
Learn Stack in C#
C# Tutorial
Learn C# Online Tutorial


Consulting