Home > Programming, QA, Test and Automation Stuffs > Debugging Techniques in C#

Debugging Techniques in C#

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).

  1. Not having very much meta-information (e.g. line number, method name, etc.)
  2. Having to add and remove debug statements whenever the debug focus shifts
  3. 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();


Font: http://www.csharp-station.com/Articles/DebuggingTechniques.aspx

  1. No comments yet.
  1. July 2, 2014 at 11:15 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: