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()); } } }
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); } }
OutputTotal 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); } }
OutputTotal number of elements in the Stack are: 6
Methods
Method | Description |
---|
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); } }
OutputTotal 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")); } }
OutputThe element Geek2 is present? :True The element Geek10 is present? :False
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