C# Stack

C# Stack<T> is a generic class in the .NET framework that represents a last-in, first-out (LIFO) data structure. It is part of the System.Collections.Generic namespace. The Stack<T> class allows you to push elements onto the stack and pop elements off the stack.

Here’s an example of how to use the Stack<T> class in C#:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a new stack of integers
        Stack<int> myStack = new Stack<int>();

        // Push elements onto the stack
        myStack.Push(10);
        myStack.Push(20);
        myStack.Push(30);

        // Pop elements off the stack
        while (myStack.Count > 0)
        {
            int element = myStack.Pop();
            Console.WriteLine(element);
        }
    }
}

In this example, we create a Stack<int> called myStack and push three integers onto it using the Push method. Then, we use a while loop to pop elements off the stack one by one using the Pop method. The Count property is used to check if there are any elements left in the stack.

The output of the above code will be:

30
20
10

The Stack<T> class provides other methods and properties as well, such as Peek to get the top element without removing it, Clear to remove all elements from the stack, and Contains to check if a specific element exists in the stack.

Note that Stack<T> is not thread-safe for multiple concurrent reads and writes. If you require thread safety, you can use ConcurrentStack<T> from the System.Collections.Concurrent namespace instead.