Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# | How to create a Stack
Next article icon

C# Stack Class

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, the Stack<T> class represents a Last-in-First-out (LIFO) collection of objects. The stack is the part of the System.Collections.Generic namespace. This class allows us to push elements onto the stack, pop elements from the stack, and peek at the top element without removing it.

  • The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.
  • If the Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation.
  • Stack accepts null as a valid value and allows duplicate elements.

Example: This example demonstrates how to use Stack to push and pop elements in LIFO order.

C#
// C# program Implementing Stack class using System; using System.Collections.Generic;  public class Geeks {     public static void Main(string[] args)     {         // Create a new stack         Stack<int> s = new Stack<int>();          // Push elements onto the stack         s.Push(1);         s.Push(2);         s.Push(3);         s.Push(4);          // Pop elements from the stack         while (s.Count > 0) {             Console.WriteLine(s.Pop());         }     } } 

Output
4 3 2 1 

Declaration of Stack

In C#, a Stack is declared using the Stack<T>class, where T is the type of element the stack will hold.

Stack<T> stackName = new Stack<T>();

Constructors

The Stack<T> class provides three constructor which are listed below in the table:

Constructor

Description

Stack()

Initializes an empty stack with the default initial capacity.

Stack(ICollection)

Initializes a new stack containing elements copied from a specified collection.

Stack(Int32)

Initializes an empty stack with a specified initial capacity or uses the default if the given capacity is smaller than the default.


Example: This example demonstrates the basic operations of Stack such as adding an element, checking the Stack size and viewing the top element without modify the stack.

C#
// C# program to perform  // different operations in stack using System; using System.Collections;  class Geeks {     public static void Main()     {         // Creating a Stack         Stack s = new Stack();          // Pushing elements into the Stack         s.Push(10);         s.Push(20);         s.Push(30);         s.Push(40);         s.Push(50);         s.Push(60);          // Displaying the count of elements in the Stack         Console.Write("Total elements in Stack: ");         Console.WriteLine(s.Count);          // Displaying the top element of the Stack without         // removing it         Console.WriteLine("Top element is: " + s.Peek());          // Displaying the top element of the Stack again         Console.WriteLine("Top element again is: "                           + s.Peek());          // Displaying the updated count of elements         Console.Write("Updated count of elements: ");         Console.WriteLine(s.Count);     } } 

Output
Total elements in Stack: 6 Top element is: 60 Top element again is: 60 Updated count of elements: 6 

Properties

The Stack<T> class provides several properties to access its state.

Property

Description

Count

Returns the number of elements currently in the stack.

IsSynchronized

Indicates whether the stack is thread-safe.

SyncRoot

Provides an object to synchronize access to the stack.


Example: This example demonstrates the total number of elements in the Stack.

C#
// C# program to get the number of  // elements contained in the stack using System; using System.Collections;  class Geeks {     public static void Main()     {         // Creating a Stack         Stack s = new Stack();          // Inserting the elements into the Stack         s.Push(10);         s.Push(20);         s.Push(30);         s.Push(40);         s.Push(50);         s.Push(60);          // Displaying the count of elements in the Stack         Console.Write(             "Total number of elements in the Stack are: ");         Console.WriteLine(s.Count);     } } 

Output
Total number of elements in the Stack are: 6 

Methods

MethodDescription
Clear()Removes all objects from the Stack.
Clone()Creates a shallow copy of the Stack.
Contains(Object)Determines whether an element is in the Stack.
CopyTo(Array, Int32)Copies the Stack to an existing one-dimensional Array, starting at the specified array index.
Equals(Object)Determines whether the specified object is equal to the current object.
GetEnumerator()Returns an IEnumerator for the Stack.
GetHashCode()Serves as the default hash function.
GetType()Gets the Type of the current instance.
MemberwiseClone()Creates a shallow copy of the current Object.
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.
Push(Object)Inserts an object at the top of the Stack.
Synchronized(Stack)Returns a synchronized (thread safe) wrapper for the Stack.
ToArray()Copies the Stack to a new array.
ToString()Returns a string that represents the current object.

Example: This example demonstrates how to use clear() to clear all the elements from the stack.

C#
// C# code to Remove all // objects from the Stack using System; using System.Collections;  class Geeks {     public static void Main()     {         // Creating a Stack         Stack s = new Stack();          // Inserting elements into the Stack         s.Push(10);         s.Push(20);         s.Push(30);         s.Push(40);         s.Push(50);         s.Push(60);          // Displaying the count of elements         //  before clearing the Stack         Console.Write(             "Total elements in Stack before clear: ");         Console.WriteLine(s.Count);          // Removing all elements from the Stack         s.Clear();          // Displaying the count of elements          // after clearing the Stack         Console.Write(             "Total elements in Stack after clear: ");         Console.WriteLine(s.Count);     } } 

Output
Total elements in Stack before clear: 6 Total elements in Stack after clear: 0 

Example: This example demonstrates how to check if a specific element is present in a stack using the Contains().

C#
// C# Program to Check if a Stack // contains an element using System; using System.Collections;  class Geeks {     public static void Main()     {          // Creating a Stack of strings         Stack s = new Stack();          // Inserting the elements into the Stack         s.Push("Geek1");         s.Push("Geek2");         s.Push("Geek3");         s.Push("Geek4");         s.Push("Geek5");          // Checking whether the element is         // present in the Stack or not         Console.WriteLine("The element Geek2 is present? :"                           + s.Contains("Geek2"));         Console.WriteLine("The element Geek10 is present? :"                           + s.Contains("Geek10"));     } } 

Output
The element Geek2 is present? :True The element Geek10 is present? :False 


Next Article
C# | How to create a Stack

S

Sahil_Bansall
Improve
Article Tags :
  • C#
  • CSharp-Collections-Namespace
  • CSharp-Stack-Class

Similar Reads

  • C# Stack Class
    In C#, the Stack<T> class represents a Last-in-First-out (LIFO) collection of objects. The stack is the part of the System.Collections.Generic namespace. This class allows us to push elements onto the stack, pop elements from the stack, and peek at the top element without removing it. The capa
    5 min read
  • C# | How to create a Stack
    Stack() constructor is used to initialize a new instance of the Stack class which will be empty and will have the default initial capacity. Stack represents a last-in, first out collection of object. It is used when you need last-in, first-out access to items. When you add an item in the list, it is
    2 min read
  • Stack.Count Property in C#
    This method(comes under System.Collections namespace) is used to get the number of elements contained in the Stack. The capacity is the number of elements that the Stack can store and the count is the number of elements that are actually in the Stack. The capacity is always greater than or equal to
    2 min read
  • Stack.IsSynchronized Property in C#
    This method(comes under System.Collections namespace) is used to get a value indicating whether access to the Stack is synchronized (thread safe) or not. To guarantee the thread safety of the Stack, all operations must be done through the wrapper returned by the Synchronized method. Also, retrieving
    2 min read
  • How to get Synchronize access to the Stack in C#
    Stack.SyncRoot Property is used to get an object which can be used to synchronize access to the Stack. Stack represents last-in, first out collection of object. It is used when you need last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you r
    3 min read
  • Stack.Clear Method in C#
    This method(comes under System.Collections namespace) is used to remove all the objects from the Stack. This method will set the Count of Stack to zero, and references to other objects from elements of the collection are also removed. This method is an O(n) operation, where n is Count. Syntax: publi
    2 min read
  • Stack.Clone() Method in C#
    This method is used to create a shallow copy of the Stack. It just creates a copy of the Stack. The copy will have a reference to a clone of the internal data array but not a reference to the original internal data array. Syntax: public virtual object Clone (); Return Value: The method returns an Ob
    2 min read
  • Stack.Contains() Method in C#
    This method(comes under System.Collections namespace) is used to check whether a specified element is present is Stack or not. Internally this method checks for equality by calling the Object.Equals method. Also, it performs a linear search, therefore, this method is an O(n) operation, where n is Co
    2 min read
  • Stack.CopyTo() Method in C#
    This method(comes under System.Collections namespace) is used to copy the Stack to an existing 1-D Array which starts from the specified array index. The elements are copied onto the array in last-in-first-out (LIFO) order, similar to the order of the elements returned by a succession of calls to Po
    2 min read
  • Stack.Equals() Method in C#
    Equals(Object) Method which is inherited from the Object class is used to check if a specified Stack class object is equal to another Stack class object or not. This method comes under the System.Collections namespace. Syntax: public virtual bool Equals (object obj); Here, obj is the object which is
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences