Csharp Stack
[ C# Collections](#)
In C#, a Stack is a Last-In-First-Out (LIFO) data structure.
A Stack is suitable for storing and processing data in order, where the most recently added element is removed first.
A Stack represents a collection of **Last-In-First-Out** objects. Use a Stack when you need last-in-first-out access to items. When you add an item to the list, it is called **pushing** an element, and when you remove an item, it is called **popping** an element.
**Stack provides two implementations:**
1. **Non-generic `Stack`** (`System.Collections.Stack`): Supports storing objects of any type (requires boxing and unboxing operations).
2. **Generic `Stack`** (`System.Collections.Generic.Stack`): Supports strongly typed objects, avoids boxing and unboxing, and improves performance.
**Stack Characteristics:**
* **Last-In-First-Out**: The last element pushed onto the stack is the first one popped off.
* **Dynamic Size**: The capacity of the stack adjusts dynamically as needed.
* **Generic Support**: Provides type safety through `Stack`, avoiding type casting errors.
* **Not Thread-Safe**: By default, both `Stack` and `Stack` are not thread-safe.
The following table lists some common **properties** of the **Stack** class:
| Property Name | Type | Description |
| --- | --- | --- |
| `Count` | `int` | Gets the number of elements in the stack. |
| `SyncRoot` | `object` | Gets an object that can be used to synchronize access to the stack (non-generic). |
| `IsSynchronized` | `bool` | Indicates whether access to the stack is synchronized (thread-safe, always `false`). |
td>Gets the number of elements contained in the Stack.
The following table lists some common **methods** of the **Stack** class:
| Method Name | Return Type | Description |
| --- | --- | --- |
| **Element Operations** | | |
| `Push(object item)` | `void` | Pushes an object onto the top of the stack. |
| `Pop()` | `object` | Removes and returns the object at the top of the stack. |
| `Peek()` | `object` | Returns the object at the top of the stack without removing it. |
| `Clear()` | `void` | Removes all objects from the stack. |
| **Checking and Copying** | | |
| `Contains(object item)` | `bool` | Determines whether an element is in the stack. |
| `ToArray()` | `object[]` | Copies the stack elements to a new array (in reverse order). |
| `Clone()` | `object` | Creates a shallow copy of the stack. |
| `CopyTo(Array array, int index)` | `void` | Copies the stack elements to an existing array, starting at a specified index. |
| **Enumerator Support** | | |
| `GetEnumerator()` | `IEnumerator` | Returns an enumerator that iterates through the stack. |
| **Thread Safety** | | |
| `Synchronized(Stack stack)` | `Stack` | Returns a thread-safe wrapper for the stack. |
The following example demonstrates the use of a Stack.
**Non-generic Stack:**
## Example
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Stack st =new Stack();
st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');
Console.WriteLine("Current stack: ");
foreach(char c in st)
{
Console.Write(c +" ");
}
Console.WriteLine();
st.Push('V');
st.Push('H');
Console.WriteLine("The next poppable value in stack: {0}",
st.Peek());
Console.WriteLine("Current stack: ");
foreach(char c in st)
{
Console.Write(c +" ");
}
Console.WriteLine();
Console.WriteLine("Removing values ");
st.Pop();
st.Pop();
st.Pop();
Console.WriteLine("Current stack: ");
foreach(char c in st)
{
Console.Write(c +" ");
}
}
}
}
When the above code is compiled and executed, it produces the following result:
Current stack: W G M A The next poppable value in stack: H Current stack: H V W G M A Removing values Current stack: G M A
**Generic Stack:**
## Example
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Stack stack =new Stack();
// Push
stack.Push(10);
stack.Push(20);
stack.Push(30);
// Peek at the top of the stack
Console.WriteLine($"Peek: {stack.Peek()}");// Output: 30
// Pop
Console.WriteLine($"Pop: {stack.Pop()}");// Output: 30
// Remaining stack
Console.WriteLine("Remaining items:");
foreach(var item in stack)
{
Console.WriteLine(item);// Output: 20, 10
}
}
}
### **Difference Between Stack and Stack**
#### **Stack (Non-generic)**
* Stores objects as type `object`.
* Requires explicit type casting when used, which may lead to runtime exceptions.
#### **Stack (Generic)**
* Provides type safety, avoiding type casting issues.
* Offers better performance by avoiding the overhead of boxing and unboxing.
[ C# Collections](#)
YouTip