- HTML Comments Tutorial | Convert Comments into HTML Codes
- Data Structure and Algorithms Tutorial | Ultimate Guide to Learn
- Gradle Tutorial | For Beginners [ STEP-IN ]
- Encapsulation In Java | Complete Tutorial With Examples
- What is Release Management? | A Comprehensive Tutorial for Beginners
- OOPs Concepts in Java | Learn from Basics with Examples
- The Top Basic Tools of Quality Tutorial | The Ultimate Guide
- Set Environment for C# – Learn How to Setup through this Tutorial
- C# Vs Java Tutorial | Overview and Key Difference
- List of IDEs to run C# Programs | Tutorial for Learning Path
- C Sharp Variables and Constants | The Ultimate Guide
- Unsafe Code in C-Sharp Tutorial | Everything You Need to Know
- Type Conversion Method in C# | A Complete Tutorial
- What Is Synchronization in c# Tutorial | The BEST Step-By-Step Guide
- Understanding Structures in C# | Learn in 1 Day FREE Tutorial
- Strings – C# Tutorial | A Definitive Programming Guide
- Static Keyword in C# Tutorial | Learn with Examples
- Stack Collection in C# Tutorial | A Definitive Guide for Beginners
- C# Sorted List Tutorial with Examples | Learn in 1 Day FREE
- C# Serialization Tutorial | Ultimate Guide to Learn [BEST & NEW]
- Regular Expression in C# Tutorial | Everything You Need to Know
- What is Reflection in C#? | Learn Now Tutorial
- Queue Collection in C# Tutorial | A Definitive Guide
- Properties in C# | The complete Tutorial
- C# Preprocessor Directives Tutorial | Learn in 1 Day FREE
- Polymorphism C# Tutorial | The Ultimate Guide
- C# Operators Tutorial | Learn Arithmetic, Comparison, Logical Concepts
- Namespaces – The complete C# Tutorial
- Multithreading in C# Tutorial | Learn With Examples and Advantages
- Methods – C# Tutorial | A Complete Programming Guide
- Linked List Implementation in C# Tutorial | Ultimate Guide to Learn [UPDATED]
- Introduction to C# Tutorial | Guide for Beginners
- What is Interface in C# | A Defined Free Tutorial
- C# Inheritance Tutorial | A Complete Free Tutorial
- Indexers in C# Tutorial | A Complete Programming Guide
- HashSet Collection in C# Tutorial | Complete Guide Tutorial For Free
- Generics in C# Tutorial | Learn Generic Classes and Methods
- Creating Your First C# Program Tutorial | Learn in 1 Day
- Basics of File Handling in C# Tutorial | The Ultimate Guide
- C# Exception Handling Tutorial | Learn with Best Practices
- Events – C# Tutorial | A Complete Programming Guide
- C# Enumerations Type Tutorial | Learn Everything about Enum
- Dictionary Collection in C# | Ultimate Guide to Learn [NEW & UPDATED]
- Delegates – C# Programming Guide | The Ultimate Guide for Beginners
- Understanding Decision Making Statements in C# | Learn Now Tutorial
- Classes and Objects – C# Fundamentals Tutorial
- C# BitArray Collection Tutorial | Learn in 1 Day FREE
- Attributes in C# Tutorial | Learn to work with attributes in C#
- C# Array Tutorial | Create, Declare, Initialize
- ArrayList Collection on in C# | A Complete tutorial For Beginners
- Anonymous Methods and Lambdas – C# Tutorial | A Complete Guide
- Abstraction in C# Tutorial – Learn the Abstract class and Interface
- Game Development using Unity 3D Tutorial | Ultimate Guide to Learn [UPDATED]
- C++ Reference Tutorial | A Comprehensive Guide for Beginners
- PHP vs Python | Which Is Better For Web Development
- C++ Constructors Tutorial: Types and Copy Constructors
- JavaScript Arrays Tutorial | Complete Beginner’s Guide
- What Is Maven | Maven Tutorial For Beginners
- Spring Tutorial | Perfect Guide for Beginners
- React Hooks Tutorial for Beginners | Ultimate Guide to Learn
- Python for Data Science Tutorial | Quickstart : A Complete Guide
- What is Golang? : A tutorial for beginners | Get started
- Hibernate Validator Tutorial | Learn in 1 Day FREE
- Postman Tutorial for Beginners: API Testing using Postman | A Complete Guide
- Akka Tutorial
- J2EE | Web Development Tutorial for Beginners
- Scala Exception Handling Tutorial | Learn in 1 Day [ STEP-IN ]
- Web development Tutorial
- Visual Studio Tutorial
- PyGame Tutorial
- Python Anaconda Tutorial
- Python Scikit-Learn Cheat Sheet Tutorial
- Mean Stack Tutorial
- Python Requests Tutorial
- Advanced Java Tutorial
- Spring Boot Microservices Tutorial
- Java Servlets Tutorial
- How to Install Pycharm
- Pycharm Tutorial
- Python Version Tutorial
- Python strings
- How to Download Python
- C Data Types Tutorial
- arrays in python
- Python While Loop Tutorial
- JAVA Tutorial
- Loops In C Tutorial
- Java File I/O Tutorial
- Variables in Python Tutorial
- Python Tutorial
- Python Pandas Cheat Sheet Tutorial
- Data Structures Cheat Sheet with Python Tutorial
- Python Tuples Tutorial
- Python If Else Statements Tutorial
- Python Functions Tutorial
- HTML Comments Tutorial | Convert Comments into HTML Codes
- Data Structure and Algorithms Tutorial | Ultimate Guide to Learn
- Gradle Tutorial | For Beginners [ STEP-IN ]
- Encapsulation In Java | Complete Tutorial With Examples
- What is Release Management? | A Comprehensive Tutorial for Beginners
- OOPs Concepts in Java | Learn from Basics with Examples
- The Top Basic Tools of Quality Tutorial | The Ultimate Guide
- Set Environment for C# – Learn How to Setup through this Tutorial
- C# Vs Java Tutorial | Overview and Key Difference
- List of IDEs to run C# Programs | Tutorial for Learning Path
- C Sharp Variables and Constants | The Ultimate Guide
- Unsafe Code in C-Sharp Tutorial | Everything You Need to Know
- Type Conversion Method in C# | A Complete Tutorial
- What Is Synchronization in c# Tutorial | The BEST Step-By-Step Guide
- Understanding Structures in C# | Learn in 1 Day FREE Tutorial
- Strings – C# Tutorial | A Definitive Programming Guide
- Static Keyword in C# Tutorial | Learn with Examples
- Stack Collection in C# Tutorial | A Definitive Guide for Beginners
- C# Sorted List Tutorial with Examples | Learn in 1 Day FREE
- C# Serialization Tutorial | Ultimate Guide to Learn [BEST & NEW]
- Regular Expression in C# Tutorial | Everything You Need to Know
- What is Reflection in C#? | Learn Now Tutorial
- Queue Collection in C# Tutorial | A Definitive Guide
- Properties in C# | The complete Tutorial
- C# Preprocessor Directives Tutorial | Learn in 1 Day FREE
- Polymorphism C# Tutorial | The Ultimate Guide
- C# Operators Tutorial | Learn Arithmetic, Comparison, Logical Concepts
- Namespaces – The complete C# Tutorial
- Multithreading in C# Tutorial | Learn With Examples and Advantages
- Methods – C# Tutorial | A Complete Programming Guide
- Linked List Implementation in C# Tutorial | Ultimate Guide to Learn [UPDATED]
- Introduction to C# Tutorial | Guide for Beginners
- What is Interface in C# | A Defined Free Tutorial
- C# Inheritance Tutorial | A Complete Free Tutorial
- Indexers in C# Tutorial | A Complete Programming Guide
- HashSet Collection in C# Tutorial | Complete Guide Tutorial For Free
- Generics in C# Tutorial | Learn Generic Classes and Methods
- Creating Your First C# Program Tutorial | Learn in 1 Day
- Basics of File Handling in C# Tutorial | The Ultimate Guide
- C# Exception Handling Tutorial | Learn with Best Practices
- Events – C# Tutorial | A Complete Programming Guide
- C# Enumerations Type Tutorial | Learn Everything about Enum
- Dictionary Collection in C# | Ultimate Guide to Learn [NEW & UPDATED]
- Delegates – C# Programming Guide | The Ultimate Guide for Beginners
- Understanding Decision Making Statements in C# | Learn Now Tutorial
- Classes and Objects – C# Fundamentals Tutorial
- C# BitArray Collection Tutorial | Learn in 1 Day FREE
- Attributes in C# Tutorial | Learn to work with attributes in C#
- C# Array Tutorial | Create, Declare, Initialize
- ArrayList Collection on in C# | A Complete tutorial For Beginners
- Anonymous Methods and Lambdas – C# Tutorial | A Complete Guide
- Abstraction in C# Tutorial – Learn the Abstract class and Interface
- Game Development using Unity 3D Tutorial | Ultimate Guide to Learn [UPDATED]
- C++ Reference Tutorial | A Comprehensive Guide for Beginners
- PHP vs Python | Which Is Better For Web Development
- C++ Constructors Tutorial: Types and Copy Constructors
- JavaScript Arrays Tutorial | Complete Beginner’s Guide
- What Is Maven | Maven Tutorial For Beginners
- Spring Tutorial | Perfect Guide for Beginners
- React Hooks Tutorial for Beginners | Ultimate Guide to Learn
- Python for Data Science Tutorial | Quickstart : A Complete Guide
- What is Golang? : A tutorial for beginners | Get started
- Hibernate Validator Tutorial | Learn in 1 Day FREE
- Postman Tutorial for Beginners: API Testing using Postman | A Complete Guide
- Akka Tutorial
- J2EE | Web Development Tutorial for Beginners
- Scala Exception Handling Tutorial | Learn in 1 Day [ STEP-IN ]
- Web development Tutorial
- Visual Studio Tutorial
- PyGame Tutorial
- Python Anaconda Tutorial
- Python Scikit-Learn Cheat Sheet Tutorial
- Mean Stack Tutorial
- Python Requests Tutorial
- Advanced Java Tutorial
- Spring Boot Microservices Tutorial
- Java Servlets Tutorial
- How to Install Pycharm
- Pycharm Tutorial
- Python Version Tutorial
- Python strings
- How to Download Python
- C Data Types Tutorial
- arrays in python
- Python While Loop Tutorial
- JAVA Tutorial
- Loops In C Tutorial
- Java File I/O Tutorial
- Variables in Python Tutorial
- Python Tutorial
- Python Pandas Cheat Sheet Tutorial
- Data Structures Cheat Sheet with Python Tutorial
- Python Tuples Tutorial
- Python If Else Statements Tutorial
- Python Functions Tutorial
Stack Collection in C# Tutorial | A Definitive Guide for Beginners
Last updated on 16th Aug 2022, Blog, Software Engineering, Tutorials
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:

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:

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 Stack | Non-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());
- }
- }