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


Methods and Properties of the Stack Class:-

Methods of Stack Class:-

Sr.No. Methods
1 public virtual void Clear();

Removes all elements from the Stack.

2 public virtual bool Contains(object obj);

Determines whether an element is in the Stack.

3 public virtual object Peek();

Returns the object at the top of the Stack without removing it.

4 public virtual object Pop();

Removes and returns the object at the top of the Stack.

5 public virtual void Push(object obj);

Inserts an object at the top of the Stack.

6 public virtual object[] ToArray();

Copies the Stack to a new array.



Properties of the Stack Class:-

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


Example of Stack class:-

 
using System;
using System.Collections;

class StackDemo
{
    public StackDemo()
    {
        Console.WriteLine("This is Stack demo::\n");
    }

    public void Show()
    {
        Stack st = new Stack();

        st.Push('S');
        st.Push('A');
        st.Push('N');
        st.Push('T');
        st.Push('O');
        st.Push('S');
        st.Push('H');

        Console.WriteLine("Current stack: ");
        foreach (char c in st)
        {
            Console.Write(c + " ");
        }

        Console.WriteLine();

        st.Push('K');
        st.Push('U');
        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 + " ");
        }
    }
}

class Test
{
    static void Main(string[] args)
    {
        StackDemo objSt = new StackDemo();
        objSt.Show();
        Console.ReadLine();
    }
}