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:
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);
}
}
}
}