Debugging Tips - Part Three

Using DebuggerStepThrough Attribute

While working on a complex code, we often come across situations where we need to debug a lot of code to find/fix the issue(s). That also includes going through lots of methods (probably related or unrelated). The .NET Framework provides a way to avoid unwanted "Step in" through the methods. Using DebuggerStepThrough (using System.Diagnostics) attribute, you can skip debugging of unwanted methods and reduce the debugging time to some extent.

For example, I have the below class file that contains two classes ( a class in which there is a method to reverse a string and a class that logs reversed string to output window). This attribute is applicable to Class, Struct, & Method.

If DebuggerStepThrough attribute is applied to the method, any breakpoints inside that method won't be hit while debugging the application. If DebuggerStepThrough attribute is applied to a class, any breakpoints inside the class will not be hit. 
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             //Console.WriteLine("test");  
  6.             string name = "TestString";  
  7.             name = ReverseString(name);  
  8.             Console.WriteLine(name);  
  9.             Logger.LogMessages(name);  
  10.    
  11.         }  
  12.    
  13.         private static string ReverseString(string name)  
  14.         {  
  15.             Debug.WriteLine(name);  
  16.             Debug.WriteLine(name.Length);  
  17.             char[] strArray = name.ToCharArray();  
  18.             Array.Reverse(strArray);  
  19.    
  20.             return new string(strArray);  
  21.         }  
  22.     }  
Second class

For this class, I know that LogMessage is no more than showing/redirecting the data variable to console/output window. So, decorating this method would skip the step in process. 
  1. public class Logger  
  2.    {  
  3.        [DebuggerStepThrough]  
  4.        public static void LogMessages(string data)  
  5.        {  
  6.            if (data==null)  
  7.            {  
  8.                Console.WriteLine("Null Variable");  
  9.            }  
  10.            else  
  11.            {  
  12.                Debug.WriteLine(data);  
  13.            }  
  14.    
  15.        }  
  16.    }  
Output
 
When you try debugging the application, it behaves like F10 (step over) instead of F11 (step in). This is a really simple example but if you are debugging some complex code and you know that certain methods are irrelevant to current issue, then this attribute would save you from accidently stepping into that method. Even though you press F11 for the method calls, it will skip the step in and control will go to the next line (if method is decorated with this attribute). 
 
 
 
 
 
 
 For other related attributes, please go through my articles mentioned below.


Recommended Free Ebook
Similar Articles