Stack class
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Contents |
[edit]
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.
[edit]
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.
[edit]
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.
[edit]
Properties
-
Count- Gets the number of elements contained in theStack.
[edit]
Methods
-
Push(element)- Adds a new object to the last position of theStack.
-
Pop()- Returns and removes the last object of theStack.
-
Peek()- Returns the object at the top of theStackwithout removing it.
-
IsEmpty()- Validates if theStackis empty.
[edit]
Adding and Removing Elements
Add elements to the stack using the Push() method. Remove elements from the stack using the Pop() method.
[edit]
Code Examples
[edit]
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);
[edit]
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();
[edit]