Skip to content
CShift0.32

Stack<T>

Struct · namespace System · Since 0.09

struct Stack<T>

A stack of values: last in, first out.

var undo = Stack<string>.Create();
undo.Push("move");
undo.Push("delete");
string last = undo.Pop(); // "delete"
if (undo.TryPop() is string s) // no panic when the stack is empty
...

Like List<T>, a Stack is a small handle to shared storage: copies see the same elements. foreach and Get(i) go from the top (the next Pop) to the bottom.

Name Description
Create A new, empty stack.
static Stack<T> Create()

A new, empty stack.

static Stack<T> Create(int capacity)

A new, empty stack with room for capacity elements before it has to grow.

Name Description
IsCreated Whether the stack has storage: made by Create(), not the zero value (which cannot change).
Count The number of elements.
Push Puts value on top of the stack.
Pop Removes and returns the top element.
TryPop Removes and returns the top element, if there is one.
Peek The top element, without removing it.
TryPeek The top element without removing it, if there is one.
Get The element index places below the top (0 is the top).
Contains Whether an element equals value (IEquatable).
Clear Removes all elements.
ToArray The elements from the top to the bottom (the order Pop would return them).
bool IsCreated()

Whether the stack has storage: made by Create(), not the zero value (which cannot change).

Since 0.26

int Count()

The number of elements.

void Push(T value)

Puts value on top of the stack.

Panics when the stack was not created (Stack<T>.IsCreated).

T Pop()

Removes and returns the top element.

Panics when the stack is empty (Stack<T>.TryPop does not).

Optional<T> TryPop()

Removes and returns the top element, if there is one.

Returns nothing (null) when the stack is empty.

T Peek()

The top element, without removing it.

Panics when the stack is empty (Stack<T>.TryPeek does not).

Optional<T> TryPeek()

The top element without removing it, if there is one.

Returns nothing (null) when the stack is empty.

T Get(int index)

The element index places below the top (0 is the top).

Panics when index is not in 0 to Count() - 1.

bool Contains(T value) where T : IEquatable<T>

Whether an element equals value (IEquatable).

void Clear()

Removes all elements.

T[] ToArray()

The elements from the top to the bottom (the order Pop would return them).