Reputation: 1712
Debug.Assert
shows a confusing message box, but I want it to just break if condition
is false
.
The following works, but is tedious to write:
#if DEBUG
if (!condition) Debugger.Break()
#endif
So I wrote the following function:
public class Util
{
[Conditional("DEBUG")]
public static void Assert(bool condition)
{
if (!condition) Debugger.Break();
}
}
It works, but it breaks in the function and not at its call site. How do I make my Assert
function behave like the Break
function it wraps?
Upvotes: 2
Views: 197
Reputation: 799
The DebuggerStepThrough
attribute as mentioned in Patrick Hofman's answer did not work in my case. I am using Visual Studio 2022, maybe they changed how the debugger handles those attributes.
I had to use the DebuggerHidden
attribute. It works with and without enabling Just my code
.
Upvotes: 1
Reputation: 156968
Matze's comment is correct. Decorating your Assert
method with the DebuggerStepThrough
attribute sets the break point on the call of the Assert
method.
Test program:
[DebuggerStepThrough]
public static void Assert(bool condition)
{
if (!condition) Debugger.Break();
}
static void Main(string[] args)
{
Assert(false); // <-- break point here
Console.ReadKey();
}
Note that you have to turn Just my code
on. Go to Options -> Debugging -> Enable Just My Code
.
Upvotes: 4