C# Stack
In C#, a Stack is a Last In First Out (LIFO) data structure.
Stack is suitable for storing and processing data in sequence, where the most recently added element is removed first.
Stack represents aLast-in, first-outCollection of objects. When you need last-in, first-out access to items, use a stack. When you add an item to the stack, it is calledPushelement, and when you remove an item from the stack, it is calledPopElement.
Stack provides two implementations:
- non-generic
Stack(System.Collections.Stack): Supports storing objects of any type (requires boxing and unboxing operations). - Generics
Stack<T>(System.Collections.Generic.Stack<T>): Supports strongly typed objects, avoids boxing and unboxing, and improves performance.
Stack features:
- Last-in, first-out: The last element pushed onto the stack is popped first.
- Dynamic size: The capacity of the stack adjusts dynamically as needed.
- Generic support: through
Stack<T>Provides type safety, avoiding type conversion errors. - Not thread-safe: default
StackandStack<T>None of them are thread-safe.
Methods and properties of the Stack class
The table below listsStackSome common class membersProperty:
| Attribute Name | Type | Description |
|---|---|---|
Count | int | Gets the number of elements in the stack. |
SyncRoot | object | Gets an object used to synchronize access to the stack (non-generic). |
IsSynchronized | bool | Indicates whether access to the stack is synchronized (thread-safe, alwaysfalse)。 |
The table below listsStackSome common class membersMethods:
| Method Name | Return Type | Description |
|---|---|---|
| Element operations | ||
Push(object item) | void | Pushes an element onto the top of the stack. |
Pop() | object | Removes and returns the element at the top of the stack. |
Peek() | object | Returns the element at the top of the stack without removing it. |
Clear() | void | Removes all elements from the stack. |
| Check and copy | ||
Contains(object item) | bool | Determines whether an element exists in the stack. |
ToArray() | object[] | Copies the elements in the stack to a new array (with the order reversed). |
Clone() | object | Creates a shallow copy of the current stack. |
CopyTo(Array array, int index) | void | Copies the elements in the stack to an existing array, starting at the specified index. |
| Enumerator support | ||
GetEnumerator() | IEnumerator | Returns an enumerator used to iterate through the elements in the stack. |
| Thread Safety | ||
Synchronized(Stack stack) | Stack | Returns a thread-safe stack wrapper. |
Example
The following example demonstrates the use of a stack (Stack).
Non-generic stack:
Example
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 results:
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.Collections.Generic;
class Program
{
static void Main()
{
Stack<int> stack = new Stack<int>();
// push
stack.Push(10);
stack.Push(20);
stack.Push(30);
// View 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<T>
Stack (non-generic)
- Stores objects as
objecttype. - Requires explicit type casting when used, which may cause runtime exceptions.
Stack<T> (Generic)
- Provides type safety and avoids type conversion issues.
- Better performance because it avoids the overhead of boxing and unboxing.