Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Debug.Assert condition as a string on fail

Tags:

c#

I'm building up tooling for a piece of software and would like to be able save out the boolean expression in the source code that exists in a Debug.Assert (or Trace.Assert) call.

For example, if the program crashes with:

var x = -1;
Debug.Assert(x >= 0, "X must be non-negative", "some detail message");

I'd like to be able to get out the string "x >= 0" as well as the message and detail message.

I've looked into using a TraceListener, but TraceListener#Fail(string) and TraceListener#Fail(string, string) only can capture the message and detail message fields (which, in the case a developer does not include, leaves me with no easy way to report what went wrong).

I suppose it's possible to create a stack trace and read the particular line that failed and report that (assuming the source code is available), but this seems relatively fragile.

Thanks for your time!

like image 517
Michael Tang Avatar asked Feb 10 '23 09:02

Michael Tang


1 Answers

You can use expressions to accomplish something rough:

public static class DebugEx
{
    [Conditional("DEBUG")]
    public static void Assert(Expression<Func<bool>> assertion, string message)
    {
        Debug.Assert(assertion.Compile()(), message, assertion.Body.ToString());
    }
}

and use it like so:

var i = -1;
DebugEx.Assert(() => i > 0, "Message");

There are some down sides to this. The first is, you have to use a lambda, so that complicates the syntax a little bit. The second is since we are dynamically compiling things, there is a performance hit. Since this will only happen in Debug mode (hence the conditional), the performance loss won't be seen in Release mode.

Lastly, the output isn't pretty. It'll look something like this:

(value(WindowsFormsApplication1.Form1+<>c__DisplayClass0).i > 0)

There isn't a whole lot you can do about this. The reason this happens is because of the closure around i. This is actually accurate since that is what it gets compiled down into.

like image 53
vcsjones Avatar answered Feb 13 '23 03:02

vcsjones