The Stack type in C#

To continue with the series on collections in C#, we will look at the stack type in C#.

 

 

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:

stack c#

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#. 

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é