Stack<T> is a strongly typed collection of values, where elements can be added or removed at the top of the stack. Stack<T> is based on LIFO principle, meaning elements can be only added to the top and only top element can be removed. Stack<T>  is an reference type. System.Collections.Generic class methods that we can use with Stack<T>.


Stack<T> can contain reference or value types. We declare a Stack<T> by typing Stack followed by<> (angle brackets) and inside <> should be our type and after that should be variable name:


As Stack<T>  is an reference type so we initialize it by assigning Stack variable to Stack<T> instance. Stack<T>  type should be specified while instantiating Stack<T>.

Populating a Stack<T> with values using Push method

Stack<T> is populated by using Push method:

Remove an element from the Stack<T>

Pop element

By using Pop method we can remove top element of the Stack<T> and get that value.

By using Pop method value will be removed from the Stack<T> and Count property will be decremented by 1.

Clear Stack

By using Clear method all Stack<T> elements will be removed from the stack.

How to use Stack<T>

Peek top value

By using Peek method we can inspect top value with no fear of popping it from the stack.

Iterate through Stack<T>

We can iterate an Stack<T> using for and foraech statements. Using these loops elements will not be popped from the Stack<T>.

Number of elements inside of a Stack<T>