C stack example LEARNOVITA

Stack Collection in C# Tutorial | A Definitive Guide for Beginners

Last updated on 16th Aug 2022, Blog, Tutorials

About author

Madhuri (C# Automation Tester )

Madhuri is a C# Automation Tester and She has tons of experience in the areas of HTTP, SOAP/REST, VisualStudio, TFS, etc., CI/CD, functional, regression, and .NET technology stack. She spends most of her time researching technology, and startups.

(5.0) | 19597 Ratings 2302

Introduction of C# Stack with Examples:

A Stack is a last-in, first-out collection of objects. It is used when needing last-in, first-out access to items. It is both a generic and non-generic type of the collection. The generic stack is explained in System.Collections.Generic namespace whereas non-generic stack is explained under System.

A stack is used to generate a dynamic collection that grows, according to the need of the program. In a stack, can save elements of the same type or various types. n c#Stack is useful for representing a collection of objects that save elements in LIFO (Last in, First out) style, i.eThe element that is added last will be the first to come out. By using Push() and Pop() / Peek() methods, you can add or retrieve an element from a stack. The Push() method is useful to add elements to the stack, and the Pop() / Peek() method is useful to retrieve the elements from the stack.

The below diagram show the Stack class hierarchy:

Important Points:

  • The Stack class implemented the IEnumerable, ICollection, and ICloneable interfaces.
  • When adding an item in the list, it is called a pushing element.
  • When removing it, it is called popping the element.
  • The capacity of a Stack is the number of elements Stack can hold.
  • As elements are added to a Stack, the capacity is automatically increased as needed through reallocation.
  • In Stack, allowed to save duplicate elements.
  • A Stack accepts null as a valid value for the reference types.

C# Stack Declaration:

C# Stack

Generally, c# will encourage both generic and non-generic types of stacks. Here, non-generic queue collections by using the System.Collections namespace can add elements of various data types. The collection is a class, so to explain stack, you need to declare an instance of the stack class before performing any operations like add, delete, etc. as shown below.

  • Stack stk = new Stack();
  • If we observe the above stack declaration, we created a new stack (stk) with an instance of stack class without specifying any size.

C# Stack Properties:

The commonly used properties of a stack in the c# programming language.

    Property Description
    Count It will return the total number of the elements in the stack.
    IsSynchronized It is used to get a value to denote that access to the stack is synchronized (thread-safe) or not.

C# Stack Methods:

The commonly used stack methods to perform operations like add, delete, etc., on elements of a stack in the c# programming language:

    Method Description
    Push It is used to insert an object at the top of the stack.
    Pop It will remove and return an object at the top of a stack.
    Clear It will remove all the elements from a stack.
    Clone It will generate a shallow copy of a stack.
    Contains It is used to find whether an element exists in a stack or not.
    Peek It is used to return a top element from a stack.

How to create a Stack?

Stack class has three constructors which are used to create a stack which are:

Stack(): This constructor is used to generate an instance of the Stack class which is empty and having default initial capacity.

Stack(ICollection): This constructor is used to generate an instance of the Stack class which includes elements copied from the specified collection, and has the same initial capacity as the number of elements copied.

Stack(Int32): This constructor is used to generate an instance of the Stack class which is empty and having specified initial capacity or the default initial capacity, whichever is greater.

How to create a stack by using Stack() constructor:

Step 1: Include System.Collections namespace in the program with the help of using keywords. using System.Collections;

Step 2: Create a stack by using Stack class as below:

Stack stack_name = new Stack();

Step 3: If you want to add elements in the stack, then use the Push() method to add elements in the stack. Here is an example.

Example:

  • // C# program to illustrate how to
  • // create a stack
  • using System;
  • using System.Collections;
  • class GFG {
  • // Main Method
  • static public void Main()
  • {
  • // Create a stack
  • // Using Stack class
  • Stack my_stack = new Stack();
  • // Adding elements in the Stack
  • // Using Push method
  • my_stack.Push(“Geeks”);
  • my_stack.Push(“geeksforgeeks”);
  • my_stack.Push(‘G’);
  • my_stack.Push(null);
  • my_stack.Push(1234);
  • my_stack.Push(490.98);
  • // Accessing the elements
  • // of my_stack Stack
  • // Using foreach loop
  • foreach(var elem in my_stack)
  • {
  • Console.WriteLine(elem);
  • }
  • }
  • }

To remove elements from the Stack:

Stack After Deletion

In Stack, allowed to remove elements from the stack. The Stack class offers two different methods to remove elements and the methods are:

Clear: This method is used to remove all the objects from a stack.

Pop: This method removes the beginning element of a stack.

To get the topmost element of the Stack:

In Stack, simply find the topmost element of the stack by using the following methods provided by the Stack class:

Pop: This method returns an object at the beginning of the stack with modification means this method removes a topmost element of the stack.

Peek: This method returns an object at the beginning of a stack without removing it.

To check the availability of elements in the stack:

In a stack, you can check whether a given element is present or not using Contains() method.If you want to find an element in a given stack use Contains() method.This method returns true if an element is present in a stack. Otherwise, return false. The Contains() method takes O(n) time to check if an element exists in a stack. This should be taken into consideration when using this method.

Generic Stack Vs Non-Generic Stack:

    Generic StackNon-Generic Stack
    Generic stack is explained under System.Collections.Generic namespace. Non-Generic stack is explained under System.Collections namespace.
    Generic stack can only save the same type of elements. Non-Generic stacks can save the same type or various types of elements.
    There is a need to explain the type of the elements in the stack. There is no need to explain the type of the elements in the stack.
    It is type-safe. It is not type-safe.

C# – Stack Class:

It represents a last-in, first out collection of the object.It is used when needing a last-in, first-out access of the items. When adding an item in the list, it is called pushing the item and when removing it, it is called popping the item.

Methods and Properties of the Stack Class:

The following table lists some generally used

properties of the Stackclass −

    Sr.No.Property & Description
    1 Count Gets the number of elements included in the Stack.

The following table lists some of the generally used

methods of the Stack class are−

    Sr.No.Method & Description
    1

    public virtual void Clear();

    Removes all the elements from a Stack.
    2

    public virtual bool Contains(object obj);

    find whether an element is in a Stack.
    3

    public virtual object Peek();

    Returns the object at the top of a Stack without removing it.
    4

    public virtual object Pop();

    Removes and returns an object at the top of a Stack.
    5

    public virtual void Push(object obj);

    Inserts an object at the top of a Stack.
    6

    public virtual object[] ToArray();

    Copies the Stack to the new array.

C# Stack<"T">

C# Stack<"T"> class is used for the push and pop elements.It used the concept of Stack arranges elements in LIFO (Last In First Out) order.It can have duplicate elements.It is found in System.Collections.Generic namespace.

C# Stack<"T"> example:

Example of generic Stack<"T"> class that saves an element using Push() method, removes elements using Pop() method and iterates elements using for-each loop.

  • using System;
  • using System.Collections.Generic;
  • public class StackExample
  • {
  • public static void Main(string[] args)
  • {
  • Stack<"string"> names = new Stack<"string">();
  • names.Push(“Sonoo”);
  • names.Push(“Peter”);
  • names.Push(“James”);
  • names.Push(“Ratan”);
  • names.Push(“Irfan”);
  • foreach (string name in names)
  • {
  • Console.WriteLine(name);
  • }
  • Console.WriteLine(“Peek element: “+names.Peek());
  • Console.WriteLine(“Pop: “+ names.Pop());
  • Console.WriteLine(“After Pop, Peek element: ” + names.Peek());
  • }
  • }

Are you looking training with Right Jobs?

Contact Us

Popular Courses