O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

19.6. Stack

As the name implies, a Stack encapsulates a standard LIFO abstract data type. You use the Pop and Push methods of the Stack class to retrieve and insert elements respectively. Like Queue, Stack also has a Peek method which returns the element that is next to be popped out without actually popping it out.

Calling Pop() on an empty Stack will result in a System.InvalidOperationException exception. To prevent that from happening, you can check the Stack's Count public property before invoking Pop().

 1: using System;
 2: using System.Collections;
 3:
 4: public class TestClass{
 5:   public static void Main(){
 6:
 7:     Stack s = new Stack();
 8:
 9:     // Using Push
10:     s.Push("A");
11:     s.Push("B");
12:     s.Push("C");
13:     PrintCollection(s);
14:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required