Is there a way to create compile time errors if a certain method is called?
As an example, what I’d like to do is prevent code in a certain project from calling System.Configuration.ConfigurationManager.AppSettings(). Is there a way to tag the project or class file to raise a compile time error IF that method is called?
I don’t think there is, so my thought is that the only way to do this is to generate an FxCop rule that would flag these calls and do it that way, but I am open to other ideas.
I am using .NET 3.5. Not sure if 4.0 code contracts can do this.
Updates
I am specifically talking about framework methods, not my own, so I cannot mark them as Obsolete.
At this point I don’t care about reflection.
Another example is System.Web.HttpUtility.HtmlEncode, which I want to find and replace with Microsoft’s AntiXss library, but I’d like to integrate some sort of check process on my build server that would check new code as well.
The tool NDepend can be used for that (Disclaimer: I am one of the developers of the tool).
You can write some Code Rules over LINQ Queries (CQLinq) to check any kind of dependency, like a method call for example. Code rules can be checked in Visual Studio after each successful compilation, or rules can be checked at build process time as well.
Such a CQLinq code rule can look like:
The rule can be specialized at whim, to forbid for example namespaces that match a regex, to contain methods that call the
get_AppSettings()getter method:From the NDepend dependency matrix or dependency graph, you can also right click a dependency (matrix cell or graph arrow) and generate a code rule that warns if the dependency exist (and then specialize the rule generated if you need):