.NET Analyzers
I have been experimenting with .NET analyzers recently. Roslyn analyzers can inspect your C# code and highlight quality or style issues that you define. I have used Roslynator with success in the past for this. Roslynator provides hundreds of analyzers, refactorings, and fixes via its Visual Studio extension.
Starting with .NET 5, there are built-in analyzers that you can enable. Violations can be configured to show as suggestion, warning, or errors and appear with the prefix "CA" or "IDE" to differentiate them from compiler errors. You can configure the violations via an .editorconfig file. For example, if you want to receive errors in your code where using directives are unnecessary, you would use the following statement:
dotnet_diagnostic.IDE0005.severity = error
You can set the rule severity of all analyzers by using the following statement:
dotnet_analyzer_diagnostic.severity = <severity>
Below are some rules that I found to be helpful. Most rules have documentation associated with it. I've linked to the Microsoft docs for the first one as an example.
- IDE0001 - Simplify name
- IDE0003 - this and Me preferences
- IDE0004 - Remove unnecessary cast
- IDE0005 - Using directive is unnecessary
- IDE0010 - Add missing cases to switch statement
- IDE0011 - Add braces
- IDE0019 - Use pattern matching to avoid 'as' followed by a 'null' check
- IDE0040 - Add accessibility modifiers
- IDE0041 - Use is null check
- IDE0044 - Add readonly modifier
- IDE0046 - Use conditional expression for return
- IDE0047 - Parentheses can be removed
- IDE0049 - Use language keywords not framework types
- IDE0051 - Remove unused private member
- IDE0052 - Remove unread private member
- IDE0055 - Formatting rules
- IDE0059 - Unnecessary assignment
- IDE0060 - Remove unused parameter
- IDE0063 - Use simple 'using' statement
- IDE0066 - Use 'switch' expression
- IDE0071 - Simplify interpolation
- IDE0090 - 'new' expression can be simplified
- IDE0120 - Simplify LINQ expression
- IDE0130 - Namespace does not match folder structure
- CA1051 - Do not declare visible instance fields
- CA1508 - Avoid dead conditional code
- CA1716 - Identifiers should not match keywords
- CA1805 - Do not initialize unnecessarily