I am using some external .net libraries (already compiled, source code not available).
I would like to have some specific method calls to generate a compiler warning.
So for example, let's say we have the following class :
public class ExternalAPI
{
public void MethodCallNotThreadSafe();
public void MethodCallThreadSafe();
}
I would like that the following in my code generates a compiler warning (which will also trigger an error since using warning as errors, but that's off topic).
ExternalAPI api = new ExternalAPI();
api.MethodCallNotThreadSafe(); //Should trigger a warning
As mentioned, I do not have the source code for the library (or for some cases I do, but do not want to use obsolete), so Obsolete attribute is not an option.
You can use the Microsoft.CodeAnalysis.BannedApiAnalyzers NuGet package.
To summarize from its documentation, after adding the package to your project/solution, add a BannedSymbols.txt to your project/solution and this to your csproj(s)
<ItemGroup>
<AdditionalFiles Include="path to BannedSymbols.txt"/>
</ItemGroup>
Now you just need to fill BannedSymbols.txt.
One line should look like
{Documentation Comment ID string for the symbol}[;Description Text]
Given you're looking to get warnings for usage of a given method (ExternalAPI.MethodCallNotThreadSafe), the first part should look like M:Namespace.Type.Method which translates to M:ApiNamespace.ExternalAPI.MethodCallNotThreadSafe for you case. The second part is optional and lets you customize the warning's message.
For example with M:ApiNamespace.ExternalAPI.MethodCallNotThreadSafe; this method isn't thread safe, doing api.MethodCallNotThreadSafe(); will give you the following warning :
RS0030 : The symbol 'ExternalAPI.MethodCallNotThreadSafe()' is banned in this project: this method isn't thread safe.
Note that if the method you target has parameters nor type parameters, you'll have to adapt the first part accordingly to target the proper overload.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With