Member-only story
Stack in C# with Examples
3 min readApr 11, 2024
Stack is related to System.Collections.Generic namespace. In, Stack elements are added and removed from the top of the stack. This is a Last-In-First-Out (LIFO) data structure approach.
Features with stack in C#:
Creating a Stack:
You need to import the System.Collections.Generic namespace to work with the Stack. To create a Stack, you can use the following code:
Example
using System;
using System.Collections.Generic;
Stack<int> stackfruitprices = new Stack<int>();
Stack<string> stackfruitnames = new Stack<string>();
Pushing Elements:
You can add elements to the top of the Stack using the Push method:
Example
stackfruitprices.Push(12);
stackfruitprices.Push(16);
stackfruitprices.Push(22);
stackfruitprices.Push(28);
stackfruitprices.Push(9);
stackfruitnames.Push("Apple");
stackfruitnames.Push("Mango");
stackfruitnames.Push("Cherry");
stackfruitnames.Push("Orange");
stackfruitnames.Push("Grape");
stackfruitnames.Push("Kiwi");
Popping Elements:
You can remove elements from the top of the Stack using the Pop method: