Stacks are the opposite of queues. A stack is a list in which the first item in is the last item to be read.
Type System.Collections.Stack .
Type the name of the stack variable that is to store the stack object, for example: msgs .
Type = .
Type new System.Collections.Stack() .
Type a semicolon ; .
Type msgs.Push("Task1"); where "Task1" is the item to add to the stack.
Type msgs.Pop(); to extract the most recent addition from the stack ( Figure 9.56 ).
void Task() { System.Collections.Stack q1 = new System.Collections.Stack(); q1. Push ("Task1"); q1. Push ("Task2"); q1. Push ("Task3"); string s1 = (string)q1. Pop (); //Task3 string s2 = (string)q1. Pop (); //Task2 string s3 = (string)q1. Pop() ; //Task1 }
Tip
As with queues, you can enumerate through the items in the stack without removing them using the foreach function ( Figure 9.57 ).
void Task() { System.Collections.Stack q1 = new System.Collections.Stack(); q1.Push("Task1"); q1.Push("Task2"); q1.Push("Task3"); foreach (string task in q1) { Response.Write(task + ","); //Prints: Task3, Task2, Task1, } }