views:

573

answers:

2

Is there a way to output a warning in the debugger if a certain method is used in the code? I have a couple of delicate methods that should only be used in exceptional cases, so I'd like to have some kind of warning output if they are actually called anywhere in the project.

Is this possible?

A: 

You can use the Debugger.WriteLine method to see messages in the Debugger

Debugger.WriteLine("Don't use this method");

This is easily missed or ignored though. A more aggressive way of preventing this may be an assert.

Debugger.Fail("Are you sure you want to use this method?");

Yet another way to achieve this would be to mark the method as deprecated. This will result in a warning at compile time vs. debug time. You mentioned there are several places where it can be validly used. In those cases you could suppresse the deprecation warning with a pragma. This means only new uses of the method would cause a compile time warning which sounds like what you're after.

JaredPar
Can this be done through Attributes instead of code lines? Basically when the app compiles, it should show up at the bottom output.
Alex
@Alex, with the obsolete attribute / deprecation route this is possible.
JaredPar
+13  A: 

You should consider using the Obsolete attribute. It allows you to mark a method which should not be used. It takes two optional parameters a message and a flag indicating if the complier should fail or raise a warning.

Aydsman