C# Stack Tutorial For Beginners With Examples

Stack is a type of collection in which the item stored last is retrieved first. This behaviour is also called as LIFO i.e. Last In First Out.
Inserting an item into a Stack is called as Pushing and removing an item is called as Popping.

Important features of C# Stack class

Below are some of the important features of a Stack class.
  • Stack allows Null values.
  • Stak allows duplicate values.
  • It has both generic and non-generic versions.

Create a Stack in C#

A Stack can be created by using the below code.
    Stack cardHolder = new Stack();
        

Add items to a C# Stack

To add items to a C# Stack the Push method is used. Since Stack follows the LIFO pattern so items are added to the top of the Stack always.
    cardHolder.Push("A");    
        

Foreach loop to access items in C# Stack

To display items stored in a Stack a foreach loop can be used.
    Stack cardHolder = new Stack();

    cardHolder.Push("A");
    cardHolder.Push("B");
    cardHolder.Push("C");

    foreach(object obj in cardHolder)
    {
        Console.WriteLine("Item: " + obj);
    }
        
Output:
Item: C
Item: B
Item: A

Methods and Properties of a C# Stack

Commonly used methods of a Stack are:
MethodDescription
ClearRemoves all the items from a Stack.
ContainsDetermines whether an item is present in a Stack.
PeekGets the first item present on top of a Stack without removing it.
PopRemoves the top most item of a Stack.
PushAdds an item to a Stack.
Commonly used properties of a Stack are:
PropertyDescription
CountReturns the number of items present in a Stack.

No comments:

Post a Comment