Stack class

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
Exam Prep. Guides
Exam 70-536 Study Guide

1. Types and collections

2. Process, threading,…
3. Embedding features
4. Serialization, I/O
5. .NET Security
6. Interop., reflection,…
7. Global., drawing, text

edit

Contents

Description

The Stack class represents a way of managing elements in a collection using the Last In First Out (LIFO) technique for adding and removing elements. LIFO simply means that the last element added to a collection will automatially be the first one removed.

LIFO In a Stack

In the Stack class elements are added to the end of a collection and removed from the end as well. In this way the last element added to the stack will also be the first one removed or retrieved.

Members

Here are some of the common members of the Stack class. For a complete listing see the MSDN Reference at the bottom of the page.

Properties

  • Count - Gets the number of elements contained in the Stack.

Methods

  • Push(element) - Adds a new object to the last position of the Stack.
  • Pop() - Returns and removes the last object of the Stack.
  • Peek() - Returns the object at the top of the Stack without removing it.
  • IsEmpty() - Validates if the Stack is empty.

Adding and Removing Elements

Add elements to the stack using the Push() method. Remove elements from the stack using the Pop() method.

Code Examples

Create and Populate a Stack

// Create stack
Stack nouns = new Stack();
 
// Populate stack
nouns.Push(cat);
nouns.Push(dog);
nouns.Push(chair);
nouns.Push(Mary);
nouns.Push(sheqhita);
nouns.Push(home);
nouns.Push(school);

Remove Elements from a Stack

//create stack
Stack employeesHired = new Stack();
 
//Populate stack
employeesHired.Push("Dan Hanks");
employeesHired.Push("Martha Billans");
employeesHired.Push("Phillis Bowman");
 
// Remove last element
string emplyeeFired = (string) employeesHired.Pop();


MSDN References




Personal tools