class represents a Last-in- First –Out (LIFO) stack of objects. It is mainly
two operation push and pop i.e. we can push (insert) items into the stack and pop (retrieve)
items into the stack. Stack is implemented a circular buffer. It is follows the
(Last-in-first-out) strategy. We can push the items into a stack and get into a
reverse order. Stack is returned as last elements as a first when you try to
retrieve the items into the stack. As elements are added to a stack, the capacity
is automatically increased as required through reallocation.
1. Stack (): initializes a new instance of the
stack class i.e. empty and has the default initial capacity.
2. Stack (ICollection): Initializes
a new instances of the stack class that contains elements copied.
3. Stack (Int 32): initializes a new
instances of the stack class i.e. empty and has the specified initial capacity
or the default initial capacity, whichever is greater.
Count: Gets the
number of elements contained in the stack.
Gets a value indicating whether access to the stack is
Some of the important
methods of stack class are:
Clear (): Removes all
objects from the stack.
Clone (): Create a
shallow copy of the stack.
(Object): Determines whether an elements is in the stack.
Peek (): Returns
the object at the top of the stack without removing it.
Pop (): Removes
and returns the object at the top of the stack.
(Object): Inserts an object at the top of the stack.
Advantage of Stack:
1. As elements are added to the stack, the capacity of a stack is
automatically increased as required through reallocation.
2. Stack accepts null as a valid value and allows
3. Also applicable thread safety of the stack class.
example, we create an instance of stack class with initial capacity
by using its default constructor and Inserting (Push) three values into the stack. After inserting
elements we have retrieve (Pop) the elements.
static void Main(string args)
Stack st = new Stack();
// Inserting(Pop) values into the stack
Console.WriteLine(@"Let us try to use stack in the program ");
// For retrieving(Pop) values from the stack
public static void PrintValues(IEnumerable MyCollection)
foreach (Object obj in MyCollection)