A stack is a technique of creating a list so that the last
item added to the list is also the first one that can be removed. It can be
illustrated as placing a few cups in a box that can receive only one on top of
another (no adjacent cup). When it comes time to get one of those cups, you must
first access the last one that was added. This technique of building a list is
referred to as first-in last-out (FILO).

To support stack types of collections, the .NET Framework
provides the Stack class. Stack is a serializable class that implements
the ICollection (giving the ability to know the number of items in the
list) and the IEnumerable (which gives the ability to use foreach)
interfaces.

Creating a Stack

The Stack class is equipped with three constructors.
The default constructor allows you to create a stack without primarily taking
any action. Here is an example:

If you create a stack with this constructor, the list is
primarily empty with a default capacity. If you want, before initializing the
list, you can specify how much space the compiler should primarily allocate for
the number of eventual items of the list. To provide this information, the Stack
class is equipped with the following constructor:

public Stack(int initialCapacity);

Adding Items to a Stack

To add an item to a stack, you can call the Push()
method of the Stack class. Its syntax is:

As mentioned previously, the Stack class overrides the GetEnumerator()
method by implementing the IEnumerable interface. This allows you to
access each member of the stack using the foreach loop. Here is an
example:

To find out if the list contains a particular item, you can
call the Contains() method of the Stack class. Its syntax is:

public virtual bool Contains(object obj);

Removing Items From a Stack

As mentioned earlier, a stack is organized so that the last
item that was added to the list is the first one to be removed. To support this
operation, the Stack class is equipped with the Pop() method. Its
syntax is:

public virtual object Pop();

When called, this method removed the last item in the stack.
If you are interested to know what item was removed, this method returns it as
an Object value.