Sebastian Negraszus
Sebastian Negraszus

Reputation: 12205

Making a third-party method [Obsolete]

If I want to declare a method in my code as deprecated / obsolete, I can add the [Obsolete] attribute to it and make the compiler emit a warning (or error) whenever the method is used.

Is it possible to achieve a similar effect for third-party methods (such as System.Console.WriteLine)? Obviously, I cannot add the attribute since I do not control the code. But maybe there is some other trick available in .NET or Visual Studio?

I'm preferably looking for an "out of the box" solution that does not require something like writing my own post-build script that manually parses the code.

Upvotes: 7

Views: 1427

Answers (3)

Monsignor
Monsignor

Reputation: 2947

Another option for ReSharper users: ExternalAnnotations.

Here is an example of adding the annotations for Selenium's WebDriver.dll:

  1. Create ExternalAnnotations folder beside *.csproj of the target project.
  2. Inside the folder create WebDriver.xml:
    <?xml version="1.0" encoding="utf-8" ?> 
    <assembly name="WebDriver">
      <member name="M:OpenQA.Selenium.INavigation.GoToUrl(System.String)">
        <attribute ctor="M:System.ObsoleteAttribute.#ctor(System.String,System.Boolean)">
          <argument>Use different overload of this method.</argument>
          <argument>true</argument>
        </attribute>
      </member>
    
  3. Reload the solution.

Upvotes: 1

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12205

You can do that by creating custom code inspection rules in ReSharper.

Go to ReSharper / Options / Code Inspection / Custom Pattern / Add Pattern, write a pattern that matches the deprecated method call and select an inspection severity such as "suggestion" or "warning". You may also write a replacement pattern that can be applied via quick fixes.

Example:

Example of one custom pattern

In this example, the System.Console was misused for logging and should be replaced by proper log4net calls.

Upvotes: 3

Bradley Uffner
Bradley Uffner

Reputation: 16991

With Visual Studio 2015 you can create live Code Analyzers that can provide custom design-time checking for virtually anything. A good tutorial is available here. These usually live as part of the solution, so so they will "follow it around" no matter where it is compiled.

Code analyzers can can raise compile time errors or warnings, and can even present a UI to automatically correct the issue. They can be VERY powerful, but writing one of these can be fairly complex depending on what you need.

A similar feature exists for previous versions of Visual Studio (2010+). It isn't as well integrated, but might work for you.

Upvotes: 7

Related Questions