Conditional method attributes

Sometimes I like to include some code which will only run when complied in Debug config. This is simple enough, just add some preprocessor commands like so:

#if DEBUG
  //Do some debug-only stuff here.
#endif

However this always looks a bit ugly to me. A much tidier way of achieving the same is to use conditional method attribute like so:

[Conditional("DEBUG")]
private void DoSomething()
{   
  //Do some debug-only stuff here.
}

The only catch with this is that the method must return void. This is necessary to allow it to be included/excluded depending on the compilation config used. It can be worked around by using reference parameters on the method itself.

Anyway, here’s a photo of a skiing penguin.

Skiing Penguin

Leave a Reply

Your email address will not be published. Required fields are marked *