What is the Stack class in C#?


Stack is used when you need a last-in, first-out access of 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.

Let us see an example of the stack class in C# −

Firstly, add elements in the Stack.

Stack st = new Stack();

st.Push('H');
st.Push('I');
st.Push('J');
st.Push('K');
st.Push('L');

Now count the number of elements in the Stack −

Console.WriteLine("Count: "+st.Count);

Let us see the complete code −

Example

 Live Demo

using System;
using System.Collections;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         Stack st = new Stack();

         st.Push('H');
         st.Push('I');
         st.Push('J');
         st.Push('K');
         st.Push('L');

         Console.WriteLine("Count: "+st.Count);
      }
   }
}

Output

Count: 5

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 21-Jun-2020

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements