Find maximum values with explicit empty-input rules in C#
For three known numbers, nested Math.Max calls are sufficient. For a sequence, use Enumerable.Max and decide what empty input means before choosing an overload or fallback.
Zero is a valid number, not a universal “no result” value. Initializing a maximum to zero gives the wrong answer for a nonempty sequence containing only negative values.
Run the scalar and sequence cases
Use the .NET 10 SDK. Create a console project in a new directory, then replace Program.cs with the example below.
dotnet new console --framework net10.0
dotnet run
Run dotnet run after saving the replacement. No additional packages are required.
using System;
using System.Linq;
Console.WriteLine($"Three values: {Math.Max(-8, Math.Max(-2, -5))}");
var readings = new[] { -8, -2, -5 };
Console.WriteLine($"Sequence: {readings.Max()}");
Console.WriteLine($"Optional empty: {Format(Array.Empty<int>().Select(x => (int?)x).Max())}");
Console.WriteLine($"Optional values: {Format(readings.Select(x => (int?)x).Max())}");
Console.WriteLine($"All null: {Format(new int?[] { null, null }.Max())}");
try {
Console.WriteLine(Array.Empty<int>().Max());
} catch (InvalidOperationException) {
Console.WriteLine("Required empty: InvalidOperationException");
}
static string Format(int? value) => value?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "none";
Expected output:
Three values: -2
Sequence: -2
Optional empty: none
Optional values: -2
All null: none
Required empty: InvalidOperationException
For a fixed number of values, Math.Max compares two operands at a time. The nested form needs no temporary array or LINQ iterator. Choose it for a small, fixed expression rather than constructing a collection solely to ask for its largest element.
Choose what absence means
The integer Max overload throws InvalidOperationException when its input has no elements. This is useful when a nonempty result is an invariant and missing data should stop the operation.
The nullable-integer overload returns null for an empty sequence or a sequence containing only nulls. The example projects each int to int? so an empty source has an explicit absence result. This keeps -2, zero and “none” distinct.
Enumerable.Max
documents these overload-specific rules.
If zero is an intentional business fallback, readings.DefaultIfEmpty(0).Max() substitutes zero only when the sequence is empty. Appending zero unconditionally would change a valid all-negative result. A null sequence is a different error from an empty sequence and still causes ArgumentNullException.
Avoid unnecessary extra enumeration
Calling Any() and then Max() can enumerate a deferred source twice. That may repeat I/O or observe different data. The nullable projection handles optional emptiness with one enumeration. Materialize a source when a stable snapshot is required and the size permits it.
These examples use integers deliberately. Floating-point inputs need an explicit policy for NaN and infinities. Do not assume all numeric overloads express the same missing-data semantics. For selecting an object by its numeric field, inspect MaxBy and decide how ties and an empty source should be handled instead of discarding the object and retaining only its field.
Source and further reading
This article revisits the problem discussed in the following original answer. The explanation and examples here are newly written for .NET 10.
-
Herman Schoenfeld’s answer
on “Is there a method to find the max of 3 numbers in C#?”, licensed under
CC BY-SA 3.0
.



Author: Herman Schoenfeld