Reputation: 167
Consider the following simple program:
using System;
namespace DebugAssertTesting
{
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Debug.Assert(6 == 7, "Bang!");
Console.WriteLine("Hello World!");
}
}
}
When compiled as a .NET Framework console app and executed, the Assert triggers and the Assert UI dialog box is displayed. (Assert failed. Abort, Retry, Ignore etc) By adding an App.Config file containing the following, the Assert UI is disabled and "Hello World!" is displayed.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.diagnostics>
<assert assertuienabled="false" />
</system.diagnostics>
</configuration>
When the same code is compiled as a .NET Core console app and executed, the Assert triggers and the app terminates. Instead of a UI dialog box, the console displays this:
Process terminated. Assertion failed.
Bang!
at DebugAssertTesting.Program.Main(String[] args) in C:\Development\DebugAssert\DebugAssert\Program.cs:line 9
C:\Development\DebugAssert\DebugAssert\bin\Debug\netcoreapp3.1\DebugAssert.exe (process 38028) exited with code -2146232797.
Is there a way to disable the Assert within a .NET Core console app like there is in a .NET Framework app? Adding an App.Config file with the content above does not affect the behaviour. (VS2019 copies the file to the output folder, renaming it as expected but the app still terminates on the Assert.)
Can the Assert behaviour be controlled by settings within the app's runtimeconfig.json file? If so, does anyone know the correct syntax? I've tried a few so far without any luck. I've searched for the equivalent of assertuienabled and drawn a blank. The Microsoft documentation for Debug.Assert clearly shows that it is supported in all .NET Core variants, but only mentions controlling via App.Config.
Upvotes: 0
Views: 2124
Reputation: 23228
You can remove the DEBUG
constant from DefineConstants
property in csproj
file, change this
<DefineConstants>DEBUG;TRACE</DefineConstants>
to just
<DefineConstants>TRACE</DefineConstants>
Or uncheck the checkbox on Build
tab of project properties
Another option is remove the DefaultTraceListener
from Trace.Listeners
collection
Trace.Listeners.RemoveAt(0);
Debug.Assert(6 == 7, "Bang!");
Console.WriteLine("Hello World!");
It'll print you Hello World!
text.
You can also add new listener and set AssertUiEnabled
or LogFileName
properties in code (in the similar way with app.config
in .NET Framework).
Last option is to override Fail
method to customize the Assert
behavior, have a look at Customizing Assert behavior article for details
Upvotes: 5