Stack<T> is a strongly typed collection of values, where elements can be added or removed at the top of the stack. Stack<T> is based on LIFO principle, meaning elements can be only added to the top and only top element can be removed. Stack<T> is an reference type. System.Collections.Generic class methods that we can use with Stack<T>.
Declaration
Stack<T> can contain reference or value types. We declare a Stack<T> by typing Stack followed by<> (angle brackets) and inside <> should be our type and after that should be variable name:
1 2 3 4 5 6 7 |
Stack<string> cityNames; Stack <int> stackOfIntegers; Stack <DateTime> importantDates; Stack <Employee> stackOfEmployees; |
Initialization
As Stack<T> is an reference type so we initialize it by assigning Stack variable to Stack<T> instance. Stack<T> type should be specified while instantiating Stack<T>.
1 2 3 4 5 6 7 8 9 |
Stack<string> cityNames = new Stack<string>(); Stack<int> stackOfIntegers = new Stack<int>(); Stack<DateTime> importantDates = new Stack<DateTime>(); Stack<Employee> stackOfEmployees = new Stack<Employee>(); var employees = new Stack<Employee>(); |
Populating a Stack<T> with values using Push method
Stack<T> is populated by using Push method:
1 2 3 4 5 6 7 |
Stack<Employee> colors = new Stack<Employee>(); colors.Push("Red"); colors.Push("Green"); colors.Push("Blue"); |
1 2 3 4 5 |
Stack<Employee> employees = new Stack<Employee>(); employees.Push( new Employee() { Id = 1, FirstName = "John", LastName = "Doe", IsFullTime = false }); employees.Push( new Employee() { Id = 2, FirstName = "John", LastName = "Smith", IsFullTime = true }); |
Remove an element from the Stack<T>
Pop element
By using Pop method we can remove top element of the Stack<T> and get that value.
1 |
string topColor = colors.Pop(); |
By using Pop method value will be removed from the Stack<T> and Count property will be decremented by 1.
Clear Stack
1 |
colors.Clear(); |
By using Clear method all Stack<T> elements will be removed from the stack.
How to use Stack<T>
Peek top value
By using Peek method we can inspect top value with no fear of popping it from the stack.
1 |
string topColor = colors.Peek(); |
Iterate through Stack<T>
We can iterate an Stack<T> using for and foraech statements. Using these loops elements will not be popped from the Stack<T>.
1 2 3 4 5 6 7 |
foreach (var color in colors) { Console.WriteLine(color); } |
1 2 3 4 5 6 7 8 9 |
for (int i = 0; i < colors.Count; i++) { var city = colors.ElementAt(i); Console.WriteLine(city); } |
Number of elements inside of a Stack<T>
1 |
int colorCount = colors.Count; |