Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert line number in Debug.Assert statement

Tags:

c#

.net

debugging

We use Debug.Assert to signal problems in our code to the developer. I would like to add the line number where the error occurs but not hard code it as this could change and we would forget to update the string.

It would be handy to add the line number of the error. Any ideas?

like image 686
Aran Mulholland Avatar asked Jun 17 '26 18:06

Aran Mulholland


1 Answers

By default, Debug.Assert already contains stack trace information:

When the application runs in user-interface mode, it displays a message box that shows the call stack with file and line numbers.

Example:

alt text

If you're not seeing file names or line numbers in your assert dialogs, then the PDB files (which are generated as part of compilation) are missing or inaccessible. The PDB files contain file and line debugging information.

There is no true equivalent of C/C++'s __FILE__ and __LINE__ magic macros in C#, but if you still want this information outside of the assert dialogs, you can use the StackTrace class to get it. This requires you to have debugging information available (the PDB files mentioned above). Since you're probably using this for development, this is a safe requirement.

using System.Diagnostics;

namespace Managed
{
    class Program
    {
        static void Main(string[] args)
        {
            AssertWithCallSite(false, "Failed!");
        }

        [Conditional("DEBUG")]
        static void AssertWithCallSite(bool condition, string message)
        {
            if (!condition)
            {
                var callSite = (new StackTrace(1, true)).GetFrame(0);

                string fileName = callSite.GetFileName();
                int lineNumber = callSite.GetFileLineNumber();

                string assertMessage = string.Format(
                    "Assert at {0}:{1}:\n{2}",
                    fileName,
                    lineNumber,
                    message
                );

                Debug.Assert(false, assertMessage);
            }
        }
    }
}
like image 58
Chris Schmich Avatar answered Jun 19 '26 07:06

Chris Schmich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!