↓ Ir para o conteúdo principal

← todas as notas

📎 Webclip

Stack in C# - Code Maze

The article presents Stack in C# as a collection that follows the last-in-first-out rule. It contrasts Stack with FIFO behavior, explains push and pop as the basic operations, and notes that Stack is useful for cases like undo-redo histories.

Reading notes
#

  • Stack in C# keeps the last added element at the top, so it is used when data must follow LIFO.
  • The non-generic Stack can store different types, but it needs casting between object and the real type.
  • Stack is the generic version and stores items of one type from System.Collections.Generic.
  • The non-generic Stack has three constructors: empty, from ICollection, and with an initial capacity.
  • The generic Stack also has three constructors: empty, from IEnumerable, and with an initial capacity.
  • Count returns how many elements are stored in the stack.
  • Push adds an item, and when the stack reaches capacity, its capacity doubles by default.
  • Peek returns the top element without removing it.
  • Peek on an empty stack throws InvalidOperationException, while TryPeek can return false safely in the generic case.
  • Pop removes and returns the top element.
  • Pop on an empty stack throws InvalidOperationException, while TryPop can return false safely in the generic case.
  • Clear removes all elements and leaves the stack empty.
  • Non-generic Stack can be wrapped with Stack.Synchronized to make access thread-safe.
  • For generic stacks, the thread-safe option is ConcurrentStack.