#843 – Using the Generic Stack Class

A 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.

            Stack<Book> pileOfBooks = new Stack<Book>();

You can now add instances of Books to the top of the stack using the Push method.

            // Push 1st book onto stack
            pileOfBooks.Push(new Book("The World According to Garp", new Person("Irving", "John")));

            // Push another.  Gatsby on "top" of stack
            pileOfBooks.Push(new 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.

            // Remove book from top
            Book bookToRead = pileOfBooks.Pop();
            Console.WriteLine(bookToRead);

843-002
843-003

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: