Stack

suggest change

Stack stores values in LIFO (last-in, first-out) order. Push(T item) adds an element, and Pop() removes and returns the element added most recently. The generic version can hold a stack of strings:

First, add the namespace:

using System.Collections.Generic;

and use it:

Stack<string> stack = new Stack<string>();
stack.Push("John");
stack.Push("Paul");
stack.Push("George");
stack.Push("Ringo");

string value;
value = stack.Pop(); // return Ringo
value = stack.Pop(); // return George
value = stack.Pop(); // return Paul
value = stack.Pop(); // return John

There is a non-generic version that stores object values. Product stands for any reference type defined elsewhere. If both System.Collections and System.Collections.Generic are imported, write System.Collections.Stack so the name is not ambiguous.

The namespace is:

using System.Collections;

A non-generic stack:

Stack stack = new Stack();
stack.Push("Hello World"); // string
stack.Push(5); // int
stack.Push(1d); // double
stack.Push(true); // bool
stack.Push(new Product()); // Product object

object value;
value = stack.Pop(); // return Product (Product type)
value = stack.Pop(); // return true (bool)
value = stack.Pop(); // return 1d (double)
value = stack.Pop(); // return 5 (int)
value = stack.Pop(); // return Hello World (string)

There is also a method called Peek() which returns the last element added but without removing it from the Stack.

Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);

var lastValueAdded = stack.Peek(); // 20

Iterating the stack yields elements in LIFO order and does not remove them:

Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
stack.Push(40);
stack.Push(50);

foreach (int element in stack)
{
   Console.WriteLine(element);
}

The output (without removing):

50
40
30
20
10

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents