Skip to main content
Version: Next

Overview

Masterly.NonEmptyList gives .NET collections that the type system guarantees are never empty. NonEmptyList<T> is a list with at least one element, so Head, Last, Max, Average and Reduce cannot fail for lack of data. Rules such as "an order has at least one line" or "a route has at least one waypoint" appear in your method signatures instead of in comments and defensive checks.

Many LINQ operators on IEnumerable<T>, such as First, Max, Average and Aggregate, throw InvalidOperationException: Sequence contains no elements when the sequence is empty. On a NonEmptyList<T> that failure cannot happen. The list keeps the guarantee through every interface it implements. Removing the last element through IList<T>, ICollection<T> or the non-generic IList throws instead of emptying the list.

The core package targets .NET 8, .NET 9 and .NET 10 and has no dependencies. It includes a Roslyn analyzer, code fixes and a source generator. Seven optional packages add support for ASP.NET Core, configuration, EF Core, Newtonsoft.Json, MessagePack, Dapper and testing.

How it works​

Working with a non-empty list has four stages. Select a stage to read its guide.

What you can do​

Where to go next​