
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use Stack class in C#?
Stack class is used in C# to represent last-in, first out collection of object. It is used when you want the last added element to be removed first, for example, stack of books.
The following are the methods of Stack class −
Sr.No | Method & Description |
---|---|
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. |
The following is the property of Stack class: Count: Gets the number of elements in the stack.
Here is an example showing how to work with Stack class and its Push() and Pop() method −
Example
using System; using System.Collections; namespace CollectionsApplication { class Program { static void Main(string[] args) { Stack st = new Stack(); st.Push('A'); st.Push('B'); st.Push('C'); st.Push('D'); Console.WriteLine("Current stack: "); foreach (char c in st) { Console.Write(c + " "); } Console.WriteLine(); st.Push('P'); st.Push('Q'); 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 + " "); } } } }
Output
Current stack: D C B A The next poppable value in stack: Q Current stack: Q P D C B A Removing values.... Current stack: C B A
- Related Questions & Answers
- Stack Class in C#
- What is the Stack class in C#?
- How to use C# BinaryReader class?
- How to use C# BinaryWriter class?
- How to use C# FileStream class?
- How to use Queue class in C#?
- How to use ArrayList class in C#?
- How to use NameValueCollection class in C#?
- Push vs pop in stack class in C#
- The Stack Class in Javascript
- How to use the directory class in C#?
- What is the Count property of Stack class in C#?
- How to use ReadKey() method of Console class in C#?
- How to use WriteLine() method of Console class in C#?
- How to create a Stack in C#?
Advertisements