Sunday 23 July 2017

DebuggerStepThrough Attribute

While working on a complex code/ software, we often come across situations where you need to debug lots of code to find/fix the issue. That also includes going through lots of methods (probably related or unrelated). .NetFramework provides way to avoid unwanted "Step in" through methods. Using DebuggerStepThrough (using System.Diagnostics) attribute, you can skip debugging of unwanted methods and reduce the debugging time to some what extent.
For example, I have 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.).

If DebuggerStepThrough attribute is applied to method, any breakpoints inside that method won't be hit while debuggin the application.

If DebuggerStepThrough attribute is applied to class, any breakpoints inside the class will not be hit.
 
class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("test");
            string name = "TestString";
            name = ReverseString(name);
            Console.WriteLine(name);
            Logger.LogMessages(name);
 
        }
 
        private static string ReverseString(string name)
        {
            Debug.WriteLine(name);
            Debug.WriteLine(name.Length);
            char[] strArray = name.ToCharArray();
            Array.Reverse(strArray);
 
            return new string(strArray);
        }
    }
Second class:
public class Logger
   {
       [DebuggerStepThrough]
       public static void LogMessages(string data)
       {
           if (data==null)
           {
               Console.WriteLine("Null Variable");
           }
           else
           {
               Debug.WriteLine(data);
           }
 
       }
   }
Output:

No comments:

Post a Comment