C# Stack
Syntax
Stack<T> stack = new Stack<T>();
Example
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
Output
[3, 2, 1]
Explanation
In C#, a Stack
is a collection that represents a last-in, first-out (LIFO) data structure. The Stack<T>
class is a generic type, which means you can create a stack of any type, such as int
, string
, or a custom class.
To create a new stack, you can use the Stack<T>
constructor without any parameters. Once you have a stack instance, you can add elements to the top of the stack using the Push()
method. To remove an element from the top of the stack, you can use the Pop()
method.
You can also use the Peek()
method to get the element at the top of the stack without removing it, or you can use the Count
property to get the number of elements in the stack.
Use
Stacks are often used in C# to implement algorithms and data structures. They are useful whenever you need to keep track of a set of elements in a last-in, first-out order.
For example, you could use a stack to implement an undo-redo feature in a word processor. Each time the user types or deletes a character, you could push the previous text onto the stack. When the user clicks "Undo", you could pop the top element from the stack and set the text to that value.
Stacks can also be used to implement other data structures, such as a depth-first search algorithm or a recursive function.
Important Points
- The
Stack<T>
class represents a last-in, first-out (LIFO) data structure. - You can create a stack of any type, such as
int
,string
, or a custom class. - The
Push()
method adds an element to the top of the stack, while thePop()
method removes an element from the top of the stack. - The
Peek()
method returns the element at the top of the stack without removing it. - The
Count
property returns the number of elements in the stack.
Summary
In C#, the Stack<T>
class is a useful data structure for implementing algorithms and keeping track of a set of elements in a last-in, first-out order. You can create a stack of any type, add elements to the top of the stack using the Push()
method, and remove elements using the Pop()
method. The Peek()
method lets you get the element at the top of the stack without removing it, and the Count
property tells you the number of elements in the stack.