Using the Generic Stack Class

stack is a data structure that allows adding elements to the top of the stack through a Push operation, or removing elements from the top of the stack through a Pop operation.
The .NET Framework includes a Stack<T> type, defined in System.Collections.Generic, that implements a stack data type.
When you declare a stack, you indicate the type of objects that the stack will contain.
1
Stack<Book> pileOfBooks = new Stack<Book>();
You can now add instances of Books to the top of the stack using the Push method.
1
2
3
4
5
// Push 1st book onto stack
<span class="skimlinks-unlinked">pileOfBooks.Push(new</span> Book("The World According to Garp", new Person("Irving", "John")));
 
// Push another.  Gatsby on "top" of stack
<span class="skimlinks-unlinked">pileOfBooks.Push(new</span> Book("The Great Gatsby", new Person("Fitzgerald", "F. Scott")));
843-001
You can remove the object from the stop of the stack using the Pop method.
1
2
3
// Remove book from top
Book bookToRead = <span class="skimlinks-unlinked">pileOfBooks.Pop</span>();
Console.WriteLine(bookToRead);
843-002
843-003