Monday, January 14, 2013

Some good to know C# attributes


Just felt like writing about a couple of C# framework attributes that I happened to use lately, and not enough programmers know about (in my opinion, and this usually surprises me).

The first (and the name of my blog) :
DebuggerStepThroughAttribute
This attribute can be used to tell the debugger not to "step-into" a piece of code, and instead, it will skip over it. The best use for this that I can think of is when using an IoC/AOP framework and you have method interceptors, debugging can be a big pain in the ass... You keep on going through each interceptor, on every method call!
All you need to do is add [DebuggerStepThrough] above your interceptor, and the code won't be debugged.
e.g.:
[DebuggerStepThrough]
public class DontDebugInterceptor : IInterceptor
{
    // do something...
}

DebuggerDisplayAttribute
This attribute is used to tell the debugger what to display when in the 'Watch' window or when hovering over the variable in debug mode. Most people know that if you override the 'ToString()' method than you get the same effect, but sometimes this just isn't possible, since you might need the 'ToString()' method for something else.
All you need to do is add [DebuggerDisplay('Some string representation')] to the field/property/class you want to modify. You can also evaluate code inside the string given to the attribute constructor, just by wrapping it with curly braces.
e.g.:
[DebuggerDisplay('This class is : {OutputClass()}')]
public class MyClass
{
    private string OutputClass()
    {
        return "Whatever you want here...";
    }
}

2 comments:

  1. Want to learn C# from basics & in most professional Code development style. I'll have you writing real working applications in no time flat-before you reach the end of course.
    Hire C# Teacher.

    ReplyDelete
  2. DebuggerStepThroughAttribute is a must when working with AOP frameworks!

    ReplyDelete