There are several ways of categorising data structures in C#: you can differentiate between generic and non-generic collections, or between mutables and immutables, etc, but I'll cover them in other articles.
Today, let’s see the difference between LIFO and FIFO structures with their two most famous implementations: the stack and the queue.
Stacks: Last In, First Out
The LIFO acronym stands for: Last In, First Out. A LIFO structure is a data structure where the data that is most accessible is on top of the pile, meaning that you first read the last items you inserted in your collection.
When we add an item, we say that we push it; when we take it back, we say we pop it.
It’s just like a stack of plates: as you put more plates on the pile, the first ones are less and less accessible, and you’re forced to remove all the new ones to get them back!
How to use stacks in C#?
In C#, to use stacks, you just need the System.Collections package, and you'll then have the Stack class available:
As you can see:
- We can easily get the current number of elements in the stack with .Count.
- We can add new elements using . Push(): this puts a new item at the top of the pile.
- When we read back our values with the iterator, we get them in reverse order: we have LIFO structure, so we first get the last element we inserted, then the last-but-one, then the first one (in our case: 3, 2, 1).
Usually, it’s better to avoid using the non-generic Stack class and instead rely on the generic version, Stack<T>. This allows you to pass in the type of elements that you'll store in your collection which is better for type checks, safety and overall code organization.
To do this, you need to use the System.Collections.Generic package instead of System.Collections. For example, in our case, we could use Stack<int>:
Using generic collections is nice because, this way, your program knows the type of items in the collection at compile time, and it gives a hint to your IDE for autocompletion/variable typing.
Here is the same for-loop using the var keyword for auto-typing with a non-generic and a generic stack: