By Rafaela Azevedo
Debugging GUI applications for me mostly consists of printing out debug statements in the form of a dialog box with some text. While this technique was helpful for small to medium size apps I find writing large apps with a dialog box popping up after every other statement is counterproductive. With this in mind, I set out to find a better method for displaying debug statements during runtime. Enter C#.
C# solves three problems I faced when designing the useful and scalable debugging system. These problems exist either in Java, C/C++, or both (my main programming languages).
Not having very much meta-information (e.g. line number, method name, etc.)
Having to add and remove debug statements whenever the debug focus shifts
Having the debug statements compiled into the program affecting performance
Ok, discussing the solution for these problems in order we’ll start with number one. Basically a few classes from the System.Reflection and System.Diagnostics namespaces solve this problem. Using the System.Diagnostics.StackFrame class the call stack can be explored and stack details such as what is on the stack level above the current one, what line is a function being called from, etc. And with the System.Reflection classes the names of functions, namespaces, variable types, etc., can be ascertained. Applying all this to the problem at hand here’s some code that retrieves the file name, line number, and method name of the function that called it.
// create the stack frame for the function that called this function
StackFrame sf = new StackFrame( 1, true );
// save the method name
string methodName = sf.GetMethod().ToString();
// save the file name
string fileName = sf.GetFileName();
// save the line number
int lineNumber = sf.GetFileLineNumber();