One of the reasons I think it's important to write this post is because if you ever wonder how certain processes work on your computers or systems, assume it's a queue, or many queues one after another. 9 out of 10 times, it will be a queue.
Index
1 - What are queues in C#
In C#, we have the Queue type, which allows us to store information in FIFO queues (First In, First Out).
Alternatively, in .NET we have the Stack<T>
type that stores information in a LIFO style (Last In, First Out), but we'll talk about Stack
another day.
To use it, you should know it works with generics, meaning Queue<T>
, and like any other queue, once an item has been read, it leaves the queue.
Therefore, we shouldn't iterate over it as we would with a list. In theory, we can, but if you're going to use the queue as if it were a list, you might as well just use List<T>
.
2 - Creating a queue and adding elements in C#
Creating a queue is as simple as instantiating it directly and then just calling the Enqueue
method.
And just like that, you've added elements to the queue.
Queue<string> marcas = new Queue<string>();
marcas.Enqueue("Audi");
marcas.Enqueue("Opel");
marcas.Enqueue("BMW");
3 - Receiving elements from a queue in C#
There are two ways to get elements from a queue.
Peek
, which is a method that returns the value of the first element, but does not remove it from the queue.Dequeue
which returns the element and removes it from the queue
Queue<string> marcas = new Queue<string>();
marcas.Enqueue("Audi");
marcas.Enqueue("Opel");
marcas.Enqueue("BMW");
Console.WriteLine($"The first brand is {marcas.Peek()}"); //Audi
Console.WriteLine($"The first brand (again) is {marcas.Dequeue()}"); //Audi
Console.WriteLine($"The second brand is {marcas.Dequeue()}"); //Opel
4 - Queues and collections in C#
Queue<T>
is inside System.Collections.Generic
and also, the .NET team has introduced several features that are included in most types within that namespace, such as being able to implement the interface IEnumerable<T>
, which allows you to iterate over the queue.
foreach(string marca in marcas)
Console.WriteLine(marca);
But as I mentioned before, if you're going to iterate "normally", it's better to use a list.
We can also convert the queue to an array, clear it using .Clear()
, or even check if an element is in the queue with .Contains(T)
.
Finally, keep in mind that you can check the size of the queue using .Count
, and this is important because if you try to access a queue element that does not exist, you'll get an InvalidOperation
exception.
Conclusion
Before finishing, I want to mention that my first technical interview in Ireland was to implement, over an array, a method that did the same as dequeue does in FIFO queues.
We've learned how to create queues in C# and how to work with them.
If there is any problem you can add a comment bellow or contact me in the website's contact form