C# Assert
last modified November 6, 2026
In this article we show how to use assertions in C#. An assertion checks a condition that the programmer believes is always true at a given point of the program. If the condition is false, there is a bug in the program.
.NET provides two assertion methods in the System.Diagnostics
namespace: Debug.Assert and Trace.Assert. Calls to
Debug.Assert are compiled only into Debug builds, while
Trace.Assert is kept in Release builds too. By default, a failed
assertion in a .NET console application prints a message with a stack trace
and terminates the process.
Assertions are a debugging tool. They are not meant for validating user
input or method arguments, and they are different from the
Assert classes of unit testing frameworks such as
MSTest or NUnit.
C# Debug.Assert
The following example uses Debug.Assert to validate a
condition.
using System.Diagnostics;
int x = 10;
int y = 20;
Debug.Assert(x < y, "x should be less than y");
Console.WriteLine("Assertion passed.");
The Debug.Assert method validates that x is less
than y. The second parameter is a message shown when the
assertion fails. The condition holds, so the program continues.
$ dotnet run Assertion passed.
C# failing assertion
In the next example, the asserted condition is false.
using System.Diagnostics;
int age = 15;
Debug.Assert(age >= 18, "Age must be at least 18");
Console.WriteLine("Assertion passed.");
The age variable does not satisfy the condition.
Debug.Assert(age >= 18, "Age must be at least 18");
The failed assertion prints the message and a stack trace and terminates the
process immediately; the last line of the program is never reached. No
exception is thrown, so the failure cannot be caught with
try/catch. The exit code 134 means that the process
was aborted.
$ dotnet run fail.cs Process terminated. Assertion failed. Age must be at least 18 at Program.<Main>$(String[] args) in /home/user/assert/fail.cs:line 5 exit code: 134
C# assertion with condition text
Since .NET 9, the message parameter of Debug.Assert has the
CallerArgumentExpression attribute. If we omit the message, the
compiler passes the text of the condition.
using System.Diagnostics;
int x = 10;
int y = 5;
Debug.Assert(x < y);
Console.WriteLine("Assertion passed.");
We assert a condition without a message.
Debug.Assert(x < y);
The output contains the failed condition x < y itself.
$ dotnet run condition.cs Process terminated. Assertion failed. x < y at Program.<Main>$(String[] args) in /home/user/assert/condition.cs:line 6
Debug and Release builds
The Debug.Assert method is marked with
[Conditional("DEBUG")]. The compiler removes its calls unless the
DEBUG symbol is defined, which is the case only for the Debug
configuration. Trace.Assert depends on the TRACE
symbol, which is defined in both configurations.
#:property PublishAot=false
using System.Diagnostics;
int x = 10;
int y = 5;
Debug.Assert(x < y, "Debug.Assert failed");
Console.WriteLine("after Debug.Assert");
Trace.Assert(x < y, "Trace.Assert failed");
Console.WriteLine("after Trace.Assert");
We have two failing assertions. We run the program in the Debug configuration first and then in the Release configuration.
#:property PublishAot=false
File-based apps are published as native code by default. We turn this off for the example; it is not needed for the assertions.
In the Debug build, the first assertion terminates the program. In the
Release build, the Debug.Assert call does not exist, so the
program continues until Trace.Assert fails.
$ dotnet run release.cs Process terminated. Assertion failed. Debug.Assert failed at Program.<Main>$(String[] args) in /home/user/assert/release.cs:line 7 $ dotnet run -c Release release.cs after Debug.Assert Process terminated. Assertion Failed Trace.Assert failed at Program.<Main>$(String[] args) in /home/user/assert/release.cs:line 10
Assertions with side effects
Since Debug.Assert calls are removed in Release builds, the
whole argument expression disappears with them. The condition must never
contain code that the program depends on.
#:property PublishAot=false
using System.Diagnostics;
List<string> words = ["sky", "cup", "war"];
Debug.Assert(words.Remove("cup"));
Console.WriteLine(string.Join(", ", words));
bool removed = words.Remove("war");
Debug.Assert(removed);
Console.WriteLine(string.Join(", ", words));
We remove words from a list.
Debug.Assert(words.Remove("cup"));
This is a bug. In the Release build, the Remove call is not
compiled at all and the word stays in the list.
bool removed = words.Remove("war");
Debug.Assert(removed);
The correct way is to perform the operation first and assert only its
result. Still, the Release output shows that cup remains in the
list, while war was removed in both builds.
$ dotnet run sideeffect.cs sky, war sky $ dotnet run -c Release sideeffect.cs sky, cup, war sky, cup
Custom trace listener
A failed assertion is reported to the trace listeners. The default listener terminates the process. We can replace it with our own listener, for instance one that throws an exception. Test frameworks do something similar.
using System.Diagnostics;
Trace.Listeners.Clear();
Trace.Listeners.Add(new ThrowingListener());
try
{
int[] vals = [3, 1, 2];
Debug.Assert(IsSorted(vals), "array must be sorted");
}
catch (AssertionException e)
{
Console.WriteLine($"caught: {e.Message}");
}
Console.WriteLine("program continues");
static bool IsSorted(int[] data)
{
for (int i = 1; i < data.Length; i++)
{
if (data[i - 1] > data[i]) return false;
}
return true;
}
class AssertionException(string message) : Exception(message);
class ThrowingListener : TraceListener
{
public override void Fail(string? message, string? detailMessage) =>
throw new AssertionException(message ?? "assertion failed");
public override void Write(string? message) { }
public override void WriteLine(string? message) { }
}
We install a listener that turns failed assertions into exceptions.
Trace.Listeners.Clear(); Trace.Listeners.Add(new ThrowingListener());
The Debug and Trace classes share the same
collection of listeners. We remove the default listener and add our own.
public override void Fail(string? message, string? detailMessage) =>
throw new AssertionException(message ?? "assertion failed");
The Fail method is called for failed assertions. We throw a
custom exception, which the program catches and continues.
$ dotnet run caught: array must be sorted program continues
Assertions and argument validation
Arguments passed to a method are under the control of the caller. Invalid arguments are expected errors and must be reported with exceptions, which work in all builds. Assertions check internal assumptions of the code.
using System.Diagnostics;
Console.WriteLine(Average([4, 5, 9]));
try
{
Console.WriteLine(Average([]));
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
static double Average(int[] vals)
{
ArgumentNullException.ThrowIfNull(vals);
if (vals.Length == 0)
{
throw new ArgumentException("The array must not be empty", nameof(vals));
}
double avg = vals.Sum() / (double) vals.Length;
Debug.Assert(avg >= vals.Min() && avg <= vals.Max());
return avg;
}
The Average method validates its argument with exceptions and
asserts the correctness of its result.
ArgumentNullException.ThrowIfNull(vals);
The ThrowIfNull helper throws an
ArgumentNullException when the argument is null.
An empty array is reported with an ArgumentException.
Debug.Assert(avg >= vals.Min() && avg <= vals.Max());
The average of numbers always lies between their minimum and maximum. If it does not, our computation is wrong. This is a typical use of an assertion.
$ dotnet run 6 The array must not be empty (Parameter 'vals')
Source
In this article we have shown how to use assertions in C#.
Author
List all C# tutorials.