To continue with the series on collections in C#, we will look at the stack type in C#.
Table of Contents
1 - What is the stack type in C#?
The Stack
type is a collection that stores elements in a LIFO (last in first out) way, meaning that the last element added will be the first in the list.
It is the opposite of the queue type that we saw previously.
You can use it with generics, using stack<T>
, or without generics, which stores objects. Honestly, I would always use generics:
As with queues, you can iterate like a list, but if you want to iterate, use a list.
2 - Creating a stack and adding elements in C#
Creating a stack
is very simple, just instantiate it and add elements using the .Push()
method.
Stack<string> marcas = new Stack<string>();
marcas.Push("Audi");
marcas.Push("Opel");
marcas.Push("BMW");
3 - Retrieving elements from a stack
To retrieve an element, you have two options:
-
Pop()
which will return the last element added to the stack, and remove it from the stack. -
Peek()
which will return the element without removing it from the stack.
Console.WriteLine($"The last brand added is {marcas.Peek()}"); //BMW
Console.WriteLine($"The last brand added (again) is {marcas.Pop()}"); //BMW
Console.WriteLine($"The second-to-last brand added is {marcas.Pop()}"); //Opel
If you try to retrieve an element but the stack is empty, it will throw an `InvalidOperationException`.
4 - Stack and collections in C#
Like queues, Stack<T>
is part of System.Collections.Generic
and implements the interface IEnumerable<T>
, which allows iteration.
foreach(string marca in marcas)
Console.WriteLine(marca);
But as with queues, if you are going to iterate in the "normal (reverse)" order, it is better to use a list.
You can also convert the stack to an array, dictionary, or list, clear it using .Clear()
, or even check if an element is in the stack using .Contains(T)
.
Conclusion
In this post, we have seen how to create a stack in C#.
In this post, we have seen how to work with a stack in C#.
If there is any problem you can add a comment bellow or contact me in the website's contact form