Skip to content

Core Concepts

Ahmad Al-freihat edited this page Jan 1, 2026 · 1 revision

Core Concepts

Properties

Property Description
Head Gets the first element (same as First)
First Gets the first element (same as Head)
Last Gets the last element
Tail Gets all elements except the first (returns null if only one element)
Init Gets all elements except the last (returns null if only one element)
Count Gets the number of elements

Head and Tail

The Head property always returns the first element safely, while Tail returns the remaining elements:

NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);

int head = numbers.Head;           // 1
NonEmptyList<int>? tail = numbers.Tail;  // [2, 3, 4, 5]

// For a single-element list
NonEmptyList<int> single = new(42);
int singleHead = single.Head;      // 42
NonEmptyList<int>? singleTail = single.Tail;  // null

Init and Last

Similarly, Init returns all elements except the last, and Last returns the final element:

NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);

int last = numbers.Last;           // 5
NonEmptyList<int>? init = numbers.Init;  // [1, 2, 3, 4]

The Non-Empty Guarantee

The fundamental invariant of NonEmptyList<T> is that it always contains at least one element. This is enforced by:

  1. Constructor: Requires at least one element
  2. Remove operations: Throw InvalidOperationException when attempting to remove the last element
  3. Clear(): Throws NotSupportedException
// Construction requires at least one element
NonEmptyList<int> list = new(1); // OK
NonEmptyList<int> empty = new(); // Compile error!

// Cannot remove the last element
NonEmptyList<int> single = new(1);
single.Remove(1); // Throws InvalidOperationException

// Cannot clear
list.Clear(); // Throws NotSupportedException

Next Steps

Clone this wiki locally