4

I am using Debug.Assert in a .NET Core 2.0 C# console application and surprised to find out that it only silently shows "DEBUG ASSERTION FAILS" in the output window without breaking into the debugger or showing any message box at all.

How can I bring this common behavior back in .NET Core 2.0?

1

2 Answers 2

4

If you don't want to hook up a custom listener, the easiest workaround is a custom Debug class, which substitutes the original one if the platform target is not the Framework:

#if !NETFRAMEWORK // this class is active for non-Framework platforms only
using System.Diagnostics;
using SystemDebug = System.Diagnostics.Debug;

namespace MyRootNamespace // so in your project this will hide the original Debug class
{
    internal static class Debug
    {
        [Conditional("DEBUG")] // the call is emitted in Debug build only
        internal static void Assert(bool condition, string message = null)
        {
            if (!condition)
                Fail(message);
        }

        [Conditional("DEBUG")]
        internal static void Fail(string message)
        {
            SystemDebug.WriteLine("Debug failure occurred - " + (message ?? "No message"));
            if (!Debugger.IsAttached)
                Debugger.Launch(); // a similar dialog, without the message, though
            else
                Debugger.Break(); // if debugger is already attached, we break here
        }

        [Conditional("DEBUG")]
        internal static void WriteLine(string message) => SystemDebug.WriteLine(message);

        // and if you use other methods from Debug, define also them here...
    }
}
#endif
Sign up to request clarification or add additional context in comments.

Comments

3

There is a GitHub issue: Debug.Assert(false) does not behave as expected compared to full CLR.

The dotnet team is waiting for more community interest:

Designing an appropriate xplat mechanism with the right configuration knobs isn't something I'd want to embark on without more community interest and input.

To bring back this behavior, we can write our own assert like pm100 did.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.