3

Custom Compiler Warnings and
C#: Create custom warning in Visual Studio if certain method is used in source code
haven't helped as they deal with code that is under the author's control.

We are using a 3rd party suite of UI controls (DevExpress) in our software and I want to generate a warning when someone uses MessageBox.Show("blah"); instead of XtraMessageBox.Show("blah");

Is there a way to do that?

Community
  • 1
  • 1
AndrewJacksonZA
  • 1,243
  • 2
  • 18
  • 31

3 Answers3

5

This sort of thing can be addressed relatively easily via a custom rule for FxCop/Visual Studio Code Analysis. If you are using Visual Studio Developer Edition, you will even see the rule failures displayed along-side your compilation warnings and errors in the IDE.

Nicole Calinoiu
  • 20,843
  • 2
  • 44
  • 49
2

While there's no way you can do real custom compile-time error in .NET, there's a number of third-party tools (both free and commercial) that can inject their validation logic into the build process, usually after the compilation.

Here are three ways I know of to solve you problem:

  1. Resharper 5.0($) will support custom rules / warnings.
  2. In PostSharp(free) you can define OnMethodBoundary aspect, overwrite its CompileTimeValidate method and emit a [post]compile-time error from it.
  3. NDepend can be integrated with your build process ($) to enforce coding policies like that
Andriy Volkov
  • 18,653
  • 9
  • 68
  • 83
1

No there is no direct way. If you think about it you are looking for a compiler warning for some code that you don't even compile.

If you really want this you could use Reflection methods on YOUR compiled assembly to check if any methods/assemblies you don't want have been called. Cecil has a lot of the functionality you need. You could then make this part of your build process.

Foxfire
  • 5,675
  • 21
  • 29