Tuesday, August 27, 2013

Hiding code from debugger in C#

Occasionally stepping through properties and methods gives no help to a developer who is trying to debug particular code. In these conditions it can be worthy to hide code from the debugger so that it is stepped over automatically.

[DebuggerStepThrough] Attribute
The .NET framework provides an attributes that you can apply to achieve stepping through the code, in some methods, properties and even entire classes, avoiding noisy and complicated debugging. Sometimes it is more convenient to hide a member or type from the debugger completely.


Example 

using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;

static void Main(string[] args)
{
    DoSomething();
}


[DebuggerStepThrough]
public static void DoSomething()
{
    Console.WriteLine("Can't stop here!"); // Breakpoint
    DoSomethingElse();
}


private static void DoSomethingElse()
{
    Console.WriteLine("Can stop here!"); // Breakpoint
}


[DebuggerHidden] Attribute
The DebuggerHidden attribute operates in a similar manner to DebuggerStepThrough. Although it cannot be applied to classes or structures, it can be added to properties and
indexers. Again, breakpoints within a decorated method will be ignored. However, when using DebuggerHidden, the member is completely hidden from the stack trace, as if it did not exist.
 
Example 

using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;

static void Main(string[] args)
{
    DoSomething();
}

[DebuggerHidden]
public static void DoSomething()
{
    Console.WriteLine("Can't stop here!"); // Breakpoint
    DoSomethingElse();
}

private static void DoSomethingElse()
{
    Console.WriteLine("Can stop here!"); // Breakpoint
}

No comments:

Post a Comment