Easy Tutorial
❮ Csharp Property Csharp Multithreading ❯

C# Stack

C# Collections

The Stack represents a last-in, first-out collection of objects. It is used when you need a last-in, first-out access to items. When you add an item to the list, it is called pushing the item, and when you remove it, it is called popping the item.

Stack Class Methods and Properties

The following table lists some commonly used properties of the Stack class:

Property Description
Count Gets the number of elements contained in the Stack.

The following table lists some commonly used methods of the Stack class:

No. Method Name & Description
1 public virtual void Clear(); <br>Removes all elements from the Stack.
2 public virtual bool Contains(<br> object obj<br>); <br>Determines whether an element is in the Stack.
3 public virtual object Peek(); <br>Returns the object at the top of the Stack without removing it.
4 public virtual object Pop(); <br>Removes and returns the object at the top of the Stack.
5 public virtual void Push(<br> object obj<br>); <br>Inserts an object at the top of the Stack.
6 public virtual object[] ToArray(); <br>Copies the Stack to a new array.

Example

The following example demonstrates the use of the Stack:

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

C# Collection

❮ Csharp Property Csharp Multithreading ❯