Queues in C#

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.

 

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.

colas fifo

 

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.

 

 

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café