Page Stats
Visitor: 215
Stack Class
The System.Collections.Stack class is a kind of collection that works on the principle of Last In First Out (LIFO), means that the item that is added last is executed first.

Push() method - Stack
Push() method is use to add an element into the stack.
Example 1: Add value into Stack using push() method.
Stack st = new Stack(); st.Push(10); //You can add any data type st.Push(20); st.Push(30); st.Push(40); foreach(int i in st) { Console.WriteLine(i); //get all elements in LIFO style. }
30
20
10
Pop() method - Stack
The Pop() method Removes and Returns the value that was added last from the stack. Calling Pop() method on empty stack will throw InvalidOperationException. Syntax: object Pop();
Example 2: Removes item from the Stack using Pop() method.
Stack st = new Stack(); st.Push(10); st.Push(20); st.Push(30); st.Push(40); int count = st.Count; Console.WriteLine("Number of elements in Stack: {0}", count); for(int i=1; i<=count; i++) { Console.WriteLine(st.Pop()); } Console.Write("Number of elements in Stack: {0}", st.Count);
40
30
20
10
Number of elements in Stack: 0
Peek() method - Stack
The Peek() method Returns the last (top-most) value from the stack. Calling Peek() method on empty stack will throw InvalidOperationException. Syntax: object Peek();
Example 3: Display value from Stack using Peek() method.
Stack st = new Stack(); st.Push(10); st.Push(20); st.Push(30); st.Push(40); Console.WriteLine(st.Peek()); Console.WriteLine(st.Peek()); Console.WriteLine(st.Peek());
40
40
Contains() method - Stack
The Contains() method checks whether the specified item exists in a Stack or not. Returns true if exists, returns false if not exists. Syntax: bool Contains(object obj);
Example 4: Check value from Stack using Contains() method.
Stack st = new Stack(); st.Push(10); st.Push(20); st.Push(30); st.Push(40); st.Contains(20); // returns true st.Contains(50); // returns false
Clear() method - Stack
The Clear() method removes all the elements from the stack. Syntax: void Clear();
Example 5: Clear all the elements from the stack.
Stack st = new Stack(); st.Push(10); st.Push(20); st.Push(30); st.Push(40); st.Clear(); Console.Write("Number of elements in Stack: {0}", st.Count);