Search code examples
c#.netlintroslyn-code-analysiseditorconfig

Is there a simple way to blacklist any particular method/property in C# now?


My team members consistently use several methods incorrectly, unintentionally, and after leaving the same feedback too many times.. I would like to flag certain built-in methods/properties as at least warnings.

I use sonar cloud, so this would automatically block any PRs from passing the build when Console.ForegroundColor, as a bad example, is referenced at all. Then the developers would remember to use our own inhouse equivalent or reach out to a lead when there truly is an exception (there have been none after 100+ occurrences) in order to mark it as "OK" and allow the build to continue.

I do have an editorconfig that I've tuned to change the severity of some preexisting rules, but in this case I'm not sure that what I'm trying to do can be accomplished solely using this file and sonar.


Solution

  • You can use the Microsoft.CodeAnalysis.BannedApiAnalyzers NuGet package to enforce an disallow-list of APIs that cannot be used. Coupled with TreatWarningsAsErrors, you could fail the build if things you don't want used are introduced by people.

    The documentation for the analyser can be found here.

    For example, you could use a rule like this in BannedSymbols.txt to encourage use of NodaTime instead of DateTime.Now:

    P:System.DateTime.Now; Use ISystemClock.GetCurrentInstant() from NodaTime instead.