C# Stack

Stack Collections come under System.Collection.Generic namespace. It stores in the LIFO form i.e. Last In First Out. Add elements using the Push() method, whereas remove using Pop().

There are two types of Stacks in C#: Generic and Non-Generic. The Generic Stack class should be preferred over Non-Generic.

Create a Stack and Push elements

To create a Stack in C#, with string elements, use <string>. Set the type in angular braces as shown below:

Let us see an example of creating a stack and pushing/adding elements. To add elements i.e., insert the object at the top of the stack, use the Push() method:

Output

Pop an element

To retrieve and remove an element from the top of the stack, use the Pop() method. Let us see an example:

Output

Peek an element

To return the element at the top of the stack, without removing it, use the Peek() method. Let us see an example:

Output

Count the number of elements

The Count property is used in C# to count the number of elements. Let us see an example:

Output

Remove all the elements

The Clear() method is used to remove all the stack elements. Let us see an example:

Output


Read More

C# - Installation and Setup
C# vs Java - Difference
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading