.NET API Documentation

MSDN Home

IStack Interface

The IStack interface defines a collection of objects that follows the last‑in, first‑out (LIFO) principle. It provides methods for pushing and popping elements.

Namespace

System.Collections

Assembly

System.Collections.dll

Inheritance

Implements: IEnumerable

Methods

SignatureDescription
void Push(object obj)Inserts an object at the top of the stack.
object Pop()Removes and returns the object at the top of the stack.
object Peek()Returns the object at the top of the stack without removing it.
bool IsEmpty { get; }Gets a value indicating whether the stack is empty.
int Count { get; }Gets the number of elements contained in the stack.

Properties

SignatureDescription
bool IsEmpty { get; }Indicates if the stack contains no elements.
int Count { get; }Number of elements in the stack.

Remarks

Implementations of IStack must provide thread‑safe operations if they are to be used concurrently. The interface does not prescribe a specific underlying data structure; typical implementations use arrays or linked lists.

Example

// Example of a simple stack implementation
class SimpleStack : IStack
{
    private readonly List<object> _items = new();

    public int Count => _items.Count;
    public bool IsEmpty => Count == 0;

    public void Push(object obj) => _items.Add(obj);
    public object Pop()
    {
        if (IsEmpty) throw new InvalidOperationException("Stack empty");
        var top = _items[^1];
        _items.RemoveAt(_items.Count - 1);
        return top;
    }
    public object Peek()
    {
        if (IsEmpty) throw new InvalidOperationException("Stack empty");
        return _items[^1];
    }
    public IEnumerator GetEnumerator() => _items.GetEnumerator();
}