3

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?

Alex
  • 75,813
  • 86
  • 255
  • 348

2 Answers2

15

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.

Adrian Clark
  • 12,449
  • 5
  • 36
  • 42
0

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
  • 733,204
  • 149
  • 1,241
  • 1,454
  • Can this be done through Attributes instead of code lines? Basically when the app compiles, it should show up at the bottom output. – Alex Jun 09 '09 at 05:16
  • @Alex, with the obsolete attribute / deprecation route this is possible. – JaredPar Jun 09 '09 at 05:20