Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. Queue<T> / Stack<T>

Queue<T> / Stack<T>

A first-in, first-out (FIFO) collection Queue<T> and a last-in, first-out (LIFO) collection Stack<T>.

Syntax

// Creates a queue (first-in, first-out).
Queue<T> queue = new Queue<T>();

// Creates a stack (last-in, first-out).
Stack<T> stack = new Stack<T>();

Method List

MethodQueue / StackDescription
Enqueue(item)QueueAdds an element to the end of the queue.
Dequeue()QueueRemoves and returns the element at the front. Throws an exception if the queue is empty.
Peek()Queue / StackReturns the element at the front (or top) without removing it.
Push(item)StackPushes an element onto the top of the stack.
Pop()StackRemoves and returns the element at the top. Throws an exception if the stack is empty.
TryDequeue(out T)QueueTries to remove and return an element; returns false if the queue is empty (no exception).
TryPop(out T)StackTries to remove and return an element; returns false if the stack is empty (no exception).
CountQueue / StackReturns the number of elements.

Sample Code

using System;
using System.Collections.Generic;

// Queue (first-in, first-out) example.
Queue<string> waitingList = new Queue<string>();
waitingList.Enqueue("Alice");
waitingList.Enqueue("Bob");
waitingList.Enqueue("Carol");

Console.WriteLine($"Front: {waitingList.Peek()}"); // Alice (not removed)
while (waitingList.Count > 0) {
	string next = waitingList.Dequeue();
	Console.WriteLine($"Processing: {next}");
}

// Stack (last-in, first-out) example.
Stack<string> history = new Stack<string>();
history.Push("Type text");
history.Push("Change text color");
history.Push("Change font");

// Simulating an "Undo" feature.
Console.WriteLine("Undo:");
while (history.Count > 0) {
	Console.WriteLine($"  Undo: {history.Pop()}");
}

// Safely retrieve elements using TryDequeue / TryPop.
Queue<int> tasks = new Queue<int>();
if (tasks.TryDequeue(out int value)) {
	Console.WriteLine($"Got: {value}");
} else {
	Console.WriteLine("The queue is empty.");
}

Overview

Queue<T> is suited for scenarios where items are processed in the order they arrive, such as customer queues, print jobs, and message queues. Stack<T> is used when you need to process the most recent operation first, such as editor undo (Undo) functionality, browser back navigation, and expression parsing.

Calling Dequeue() or Pop() on an empty collection throws an exception. Use TryDequeue() or TryPop() for safe retrieval.

For a collection without duplicates, see HashSet<T>.

If you find any errors or copyright issues, please .