### Default Configuration Example
Source: https://github.com/dotnet/roslynator/blob/main/src/Tools/ConfigurationFileGenerator/configuration.md
This is an example of a default configuration file for Roslynator. It must contain 'is_global = true' and cannot have section headers.
```ini
is_global = true
roslynator_analyzers.enabled_by_default = true
```
--------------------------------
### Install Roslynator CLI Tool
Source: https://github.com/dotnet/roslynator/blob/main/src/CommandLine/docs/NetCore/NuGetReadme.md
Run this command to install the Roslynator command-line tool globally.
```shell
dotnet tool install -g roslynator.dotnet.cli
```
--------------------------------
### Install Roslynator NuGet Packages
Source: https://context7.com/dotnet/roslynator/llms.txt
Add these NuGet packages to your project to include Roslynator analyzers, formatting rules, client libraries, or testing frameworks.
```xml
all
runtime; build; native; contentfiles; analyzers
all
runtime; build; native; contentfiles; analyzers
```
--------------------------------
### CLI Spellcheck Command
Source: https://github.com/dotnet/roslynator/blob/main/ChangeLog.md
Example of using the Roslynator CLI for spellchecking file names. This command helps maintain consistent naming conventions.
```bash
roslynator spellcheck --scope file-name
```
--------------------------------
### Generate API documentation with Roslynator CLI
Source: https://context7.com/dotnet/roslynator/llms.txt
Generate API reference documentation from XML doc-comments to Markdown or HTML. Use `roslynator generate-doc-root` for the documentation root index.
```bash
# Generate Markdown documentation for public API
roslynator generate-doc MySolution.sln \
--output docs/api \
--host github
# Generate documentation root index
roslynator generate-doc-root MySolution.sln \
--output docs/api/README.md
```
--------------------------------
### Format Solution with Roslynator CLI
Source: https://context7.com/dotnet/roslynator/llms.txt
Apply formatting rules to ensure consistent code style across the entire solution or project.
```sh
# Format entire solution in-place
roslynator format MySolution.sln
# Format with verbose output
roslynator format MySolution.sln --verbosity detailed
# Expected output:
# Formatting 'MySolution.sln'
# 3 file(s) formatted
```
--------------------------------
### Analyze Solution with Roslynator CLI
Source: https://context7.com/dotnet/roslynator/llms.txt
Run configured analyzers against a solution or project. Supports various output formats and severity filtering.
```sh
# Analyze a solution and output results to console
roslynator analyze MySolution.sln
# Analyze with specific severity threshold, output as JSON
roslynator analyze MySolution.sln \
--severity-level warning \
--output diagnostics.json \
--format json
# Analyze only a specific project, suppressing info-level diagnostics
roslynator analyze src/MyProject/MyProject.csproj \
--severity-level warning \
--ignored-diagnostics RCS1090
# Expected console output:
# [warning] RCS1074: Remove redundant constructor (MyClass.cs:12)
# [warning] RCS1085: Use auto-property (MyService.cs:34)
# 2 diagnostic(s) found
```
--------------------------------
### List Symbols with Roslynator CLI
Source: https://context7.com/dotnet/roslynator/llms.txt
List all declared symbols in a solution, with options to filter by visibility, kind, and output format.
```sh
# List all public types and members
roslynator list-symbols MySolution.sln \
--visibility public \
--symbol-kind type member
# Output to HTML
roslynator list-symbols MySolution.sln \
--output symbols.html \
--format html \
--visibility public internal
# Expected text output:
# Roslynator.CSharp.CSharpFactory (class)
# PredefinedBoolType() : PredefinedTypeSyntax
# PredefinedIntType() : PredefinedTypeSyntax
```
--------------------------------
### Analyze Project/Solution with Roslynator
Source: https://github.com/dotnet/roslynator/blob/main/src/CommandLine/docs/NetCore/NuGetReadme.md
Use this command to perform code analysis on your project or solution.
```shell
roslynator analyze
```
--------------------------------
### Add Roslynator.Formatting.Analyzers Package
Source: https://github.com/dotnet/roslynator/blob/main/src/Formatting.Analyzers.CodeFixes/docs/NuGetReadme.md
Use this command to add the Roslynator.Formatting.Analyzers package to your .NET project.
```shell
dotnet add package roslynator.formatting.analyzers
```
--------------------------------
### Add Roslynator.CodeAnalysis.Analyzers Package
Source: https://github.com/dotnet/roslynator/blob/main/src/CodeAnalysis.Analyzers.CodeFixes/docs/NuGetReadme.md
Use this command to add the Roslynator.CodeAnalysis.Analyzers package to your project.
```shell
dotnet add package roslynator.codeanalysis.analyzers
```
--------------------------------
### Count lines of code with Roslynator CLI
Source: https://context7.com/dotnet/roslynator/llms.txt
Count logical and physical lines of code per project. Use `roslynator loc` for logical lines and `roslynator physical-loc` for physical lines.
```bash
# Count logical lines of code
roslynator loc MySolution.sln
# Count physical lines
roslynator physical-loc MySolution.sln
```
--------------------------------
### Add Roslynator.Analyzers Package
Source: https://github.com/dotnet/roslynator/blob/main/src/Analyzers.CodeFixes/docs/NuGetReadme.md
Use this command to add the Roslynator.Analyzers package to your .NET project.
```shell
dotnet add package roslynator.analyzers
```
--------------------------------
### Simplify LINQ Query: Average and Sum
Source: https://github.com/dotnet/roslynator/blob/main/ChangeLog.md
Demonstrates simplification of LINQ queries for Average and Sum operations. Use this to make your LINQ code more concise.
```csharp
items.Select(selector).Average() => items.Average(selector)
items.Select(selector).Sum() => items.Sum(selector)
```
--------------------------------
### Creating Syntax Nodes with CSharpFactory
Source: https://context7.com/dotnet/roslynator/llms.txt
CSharpFactory simplifies the creation of predefined type syntax nodes and common trivia. It is built on top of SyntaxFactory.
```csharp
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslynator.CSharp;
// Create predefined type references
PredefinedTypeSyntax boolType = CSharpFactory.PredefinedBoolType(); // bool
PredefinedTypeSyntax intType = CSharpFactory.PredefinedIntType(); // int
PredefinedTypeSyntax stringType = CSharpFactory.PredefinedStringType(); // string
PredefinedTypeSyntax voidType = CSharpFactory.PredefinedVoidType(); // void
// Create an environment-appropriate newline trivia
var newLine = CSharpFactory.NewLine(); // \r\n on Windows, \n on Unix
```
--------------------------------
### Add Roslynator.Refactorings Package
Source: https://github.com/dotnet/roslynator/blob/main/src/Refactorings/docs/NuGetReadme.md
Use this command to add the Roslynator.Refactorings package to your .NET project.
```shell
dotnet add package roslynator.refactorings
```
--------------------------------
### Add Roslynator.CodeFixes Package
Source: https://github.com/dotnet/roslynator/blob/main/src/CodeFixes/docs/NuGetReadme.md
Use this command to add the Roslynator.CodeFixes package to your .NET project.
```shell
dotnet add package roslynator.codefixes
```
--------------------------------
### Rename Symbols with Roslynator CLI
Source: https://context7.com/dotnet/roslynator/llms.txt
Bulk rename symbols in a solution using regular expressions for pattern matching and replacement.
```sh
# Rename all async methods that don't end with "Async" suffix
roslynator rename-symbol MySolution.sln \
--symbol-kind method \
--regex "^(?!.*Async$).*$" \
--replacement "${0}Async"
```
--------------------------------
### Roslynator Configuration JSON
Source: https://context7.com/dotnet/roslynator/llms.txt
Configure Roslynator settings using a JSON file. Options include prefixing field identifiers with an underscore, setting maximum line length, and enabling or disabling root namespace.
```json
// roslynator.json
{
"prefixFieldIdentifierWithUnderscore": true,
"maxLineLength": 140,
"rootNamespaceEnabled": false
}
```
--------------------------------
### Analyze Null-Check Expressions with Roslynator
Source: https://context7.com/dotnet/roslynator/llms.txt
Use NullCheckExpressionInfo to recognize various null-check patterns in C# code. This requires importing Roslynator.CSharp and Roslynator.CSharp.Syntax namespaces. The info object provides details about the expression, whether it's a null or not-null check, and the specific style used.
```csharp
using Microsoft.CodeAnalysis;
using Roslynator.CSharp;
using Roslynator.CSharp.Syntax;
void AnalyzeCondition(SyntaxNode conditionNode, SemanticModel model)
{
// Recognize any null check style
NullCheckExpressionInfo info = SyntaxInfo.NullCheckExpressionInfo(
conditionNode,
NullCheckStyles.All);
if (!info.Success) return;
// The operand being checked
var expr = info.Expression; // e.g. "myObject"
bool isNullCheck = info.IsCheckingNull; // true for == null / is null
bool isNotNullCheck = info.IsCheckingNotNull; // true for != null / is not null
// Check what specific style was matched
switch (info.Style)
{
case NullCheckStyles.EqualsToNull: /* x == null */ break;
case NullCheckStyles.NotEqualsToNull: /* x != null */ break;
case NullCheckStyles.IsNull: /* x is null */ break;
case NullCheckStyles.IsNotNull: /* x is not null */ break;
}
}
```
--------------------------------
### Configure Roslynator Diagnostics
Source: https://context7.com/dotnet/roslynator/llms.txt
Configure Roslynator diagnostics using .editorconfig or roslynator.json files. Severity levels can be set to 'none' to disable specific rules.
```ini
# .editorconfig — configure Roslynator rules
[*.cs]
# Disable "use auto-property" suggestion
dotnet_diagnostic.RCS1085.severity = none
```
--------------------------------
### Configure Roslynator Settings
Source: https://context7.com/dotnet/roslynator/llms.txt
Configure Roslynator settings in a .editorconfig file. Severity can be set to warning, error, etc. ConfigureAwait call requirement can be enabled or disabled. Accessibility modifier preference can be set to explicit.
```ini
dotnet_diagnostic.RCS1007.severity = warning
# Configure ConfigureAwait call requirement
roslynator_configure_await = true
# Set accessibility modifier preference
roslynator_accessibility_modifiers = explicit
```
--------------------------------
### Simplify OrderBy and Reverse in C#
Source: https://github.com/dotnet/roslynator/blob/main/ChangeLog.md
Replaces `x.OrderBy(y => y).Reverse()` with `x.OrderByDescending(y => y)` for more concise sorting operations. This applies to C# code analysis.
```csharp
x.OrderBy(y => y).Reverse()
```
```csharp
x.OrderByDescending(y => y)
```
--------------------------------
### Use C# SyntaxNode extensions for properties and methods
Source: https://context7.com/dotnet/roslynator/llms.txt
Leverage `SyntaxExtensions` for convenient access to C# syntax node properties like getters, setters, and bodies. The `BodyOrExpressionBody()` method works for both block and expression bodies.
```csharp
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslynator.CSharp;
void InspectProperty(PropertyDeclarationSyntax prop)
{
// Get the getter accessor (null if none)
AccessorDeclarationSyntax? getter = prop.AccessorList?.Getter();
// Get the setter accessor (works for both 'set' and 'init')
AccessorDeclarationSyntax? setter = prop.AccessorList?.Setter();
if (getter is not null)
{
bool isAutoImplemented = getter.IsAutoImplemented();
// Returns body OR expression body (whichever is present)
CSharpSyntaxNode? body = getter.BodyOrExpressionBody();
}
}
void InspectMethod(MethodDeclarationSyntax method)
{
// True if the method contains any expression body
CSharpSyntaxNode? body = method.BodyOrExpressionBody();
bool hasExpressionBody = body is ArrowExpressionClauseSyntax;
}
```
--------------------------------
### Querying Semantic Model with SemanticModelExtensions
Source: https://context7.com/dotnet/roslynator/llms.txt
Use SemanticModelExtensions to resolve symbols from syntax, find enclosing scopes, and query the semantic model. Ensure you have the necessary using directives.
```csharp
using System.Threading;
using Microsoft.CodeAnalysis;
using Roslynator;
void AnalyzeNode(SemanticModel model, SyntaxNode node, CancellationToken ct)
{
// Resolve the symbol bound to any expression
ISymbol? symbol = model.GetSymbol(node, ct);
// Get the enclosing named type at a given position
INamedTypeSymbol? containingType = model.GetEnclosingNamedType(node.SpanStart, ct);
// Get the enclosing method or any symbol type
IMethodSymbol? containingMethod =
model.GetEnclosingSymbol(node.SpanStart, ct);
if (symbol is IMethodSymbol method)
{
// Check if method overrides something
IMethodSymbol? overridden = method.OverriddenMethod;
}
}
```
--------------------------------
### Fix Project/Solution with Roslynator
Source: https://github.com/dotnet/roslynator/blob/main/src/CommandLine/docs/NetCore/NuGetReadme.md
Execute this command to automatically fix code issues in your project or solution.
```shell
roslynator fix
```
--------------------------------
### Parse C# null check patterns with SyntaxInfo
Source: https://context7.com/dotnet/roslynator/llms.txt
Use `SyntaxInfo.NullCheckExpressionInfo` to parse conditions like `x == null` or `x is null`. Ensure the `NullCheckStyles` enum is used to specify the desired check styles.
```csharp
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslynator.CSharp;
using Roslynator.CSharp.Syntax;
// Analyzer context callback
void AnalyzeIfStatement(SyntaxNodeAnalysisContext context)
{
var ifStatement = (IfStatementSyntax)context.Node;
// Match "if (x == null)" or "if (x is null)" – both NullCheckStyles
SimpleIfStatementInfo simpleIf = SyntaxInfo.SimpleIfStatementInfo(ifStatement);
if (!simpleIf.Success) return;
NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(
simpleIf.Condition,
NullCheckStyles.EqualsToNull | NullCheckStyles.IsNull);
if (!nullCheck.Success) return;
// nullCheck.Expression → the expression being checked (e.g. "x")
// nullCheck.IsCheckingNull → true
context.ReportDiagnostic(Diagnostic.Create(Rule, simpleIf.IfStatement.GetLocation()));
}
// Parse an assignment "x = someValue"
void AnalyzeAssignment(SyntaxNodeAnalysisContext context)
{
SimpleAssignmentExpressionInfo assignment =
SyntaxInfo.SimpleAssignmentExpressionInfo(context.Node);
if (!assignment.Success) return;
ExpressionSyntax left = assignment.Left; // "x"
ExpressionSyntax right = assignment.Right; // "someValue"
}
// Parse "collection.Where(predicate)" invocation
void AnalyzeInvocation(SyntaxNodeAnalysisContext context)
{
SimpleMemberInvocationExpressionInfo invocation =
SyntaxInfo.SimpleMemberInvocationExpressionInfo(context.Node);
if (!invocation.Success) return;
string methodName = invocation.NameText; // "Where"
ExpressionSyntax receiver = invocation.Expression; // "collection"
ArgumentListSyntax args = invocation.ArgumentList;
}
```
--------------------------------
### Obfuscate all symbols
Source: https://github.com/dotnet/roslynator/blob/main/src/CommandLine.DocumentationGenerator/data/rename-symbol_bottom.md
Renames all symbols in a solution to random names. Ensure the solution file and the new name file exist in the current directory.
```shell
roslynator rename-symbol my.sln
--match "true"
--new-name "obfuscate.cs"
```
```cs
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
public class Obfuscate
{
public string GetNewName(ISymbol symbol)
{
while (true)
{
string name = Path.GetRandomFileName();
if (Regex.IsMatch(name, @"^\D"))
return Path.GetFileNameWithoutExtension(name) + "xyz";
}
}
}
```
--------------------------------
### Simplify string comparison in C#
Source: https://github.com/dotnet/roslynator/blob/main/ChangeLog.md
Replaces `x == ""` with `string.IsNullOrEmpty(x)` for better code clarity and efficiency. This applies to C# code analysis.
```csharp
x == ""
```
```csharp
string.IsNullOrEmpty(x)
```
--------------------------------
### Remove empty line between documentation comment and declaration in C#
Source: https://github.com/dotnet/roslynator/blob/main/ChangeLog.md
Illustrates the removal of unnecessary empty lines between documentation comments and code declarations for cleaner C# code.
```csharp
remove empty line between documentation comment and declaration
```
--------------------------------
### Configure Roslynator Analyzers and Refactorings with EditorConfig
Source: https://github.com/dotnet/roslynator/blob/main/src/VisualStudioCode/package/README.md
Use an EditorConfig file to set severity levels for analyzers, enable/disable analyzers, refactorings, and compiler diagnostic fixes. Specific options include setting severity for categories, individual analyzers, and specific refactorings or fixes.
```editorconfig
# Set severity for all analyzers that are enabled by default (https://docs.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2022#set-rule-severity-of-multiple-analyzer-rules-at-once-in-an-editorconfig-file)
dotnet_analyzer_diagnostic.category-roslynator.severity = default|none|silent|suggestion|warning|error
# Enable/disable all analyzers by default.
# NOTE: This option can be used only in .roslynatorconfig file
roslynator_analyzers.enabled_by_default = true|false
# Set severity for a specific analyzer
dotnet_diagnostic..severity = default|none|silent|suggestion|warning|error
# Enable/disable all refactorings
roslynator_refactorings.enabled = true|false
# Enable/disable specific refactoring
roslynator_refactoring..enabled = true|false
# Enable/disable all compiler diagnostic fixes
roslynator_compiler_diagnostic_fixes.enabled = true|false
# Enable/disable specific compiler diagnostic fix
roslynator_compiler_diagnostic_fix..enabled = true|false
```
--------------------------------
### Fix Diagnostics with Roslynator CLI
Source: https://context7.com/dotnet/roslynator/llms.txt
Apply all available code fixes non-interactively across a solution or project. The tool runs multiple fixup passes.
```sh
# Fix all auto-fixable diagnostics in a solution
roslynator fix MySolution.sln
# Fix with limited diagnostic scope and dry-run (analyze only)
roslynator fix MySolution.sln \
--diagnostics RCS1077 RCS1074 \
--max-iterations 5
# Expected output:
# Fixing 'MySolution.sln'
# Applying fixes (iteration 1)
# 12 fix(es) applied
# Applying fixes (iteration 2)
# 0 fix(es) applied
# Done fixing 'MySolution.sln'
```
--------------------------------
### Ordering Modifiers with ModifierList
Source: https://context7.com/dotnet/roslynator/llms.txt
ModifierList utilities help find the correct insertion index for new modifiers according to standard C# modifier ordering rules. This ensures modifiers are placed correctly in the syntax tree.
```csharp
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslynator.CSharp;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
void AddStaticModifier(MethodDeclarationSyntax method)
{
SyntaxToken staticToken = Token(SyntaxKind.StaticKeyword);
// Find the correct position to insert 'static' among existing modifiers
int insertIndex = ModifierList.GetInsertIndex(
method.Modifiers,
SyntaxKind.StaticKeyword);
SyntaxTokenList newModifiers = method.Modifiers.Insert(insertIndex, staticToken);
MethodDeclarationSyntax newMethod = method.WithModifiers(newModifiers);
// Result: "public static void MyMethod()" with properly ordered modifiers
}
```
--------------------------------
### Spellcheck code with Roslynator CLI
Source: https://context7.com/dotnet/roslynator/llms.txt
Find potential spelling mistakes in symbol names, comments, and string literals. Use `--interactive false` for non-interactive mode.
```bash
# Spellcheck entire solution interactively
roslynator spellcheck MySolution.sln
# Non-interactive, output results only
roslynator spellcheck MySolution.sln \
--interactive false \
--min-word-length 4
```
--------------------------------
### Checking Declaration Accessibility with SyntaxAccessibility
Source: https://context7.com/dotnet/roslynator/llms.txt
SyntaxAccessibility provides helpers to determine the declared or default accessibility of C# declaration nodes. It helps in understanding the effective accessibility.
```csharp
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslynator.CSharp;
void CheckAccessibility(MemberDeclarationSyntax member)
{
// Get the accessibility explicitly written in source
Accessibility declared = SyntaxAccessibility.GetAccessibility(member);
// e.g. Accessibility.Public, Accessibility.Private, Accessibility.NotApplicable
// Get the effective default accessibility when none is written
Accessibility defaultAcc = SyntaxAccessibility.GetDefaultAccessibility(member);
// Get effective accessibility (declared if present, otherwise default)
Accessibility effective = SyntaxAccessibility.GetEffectiveAccessibility(member);
if (effective == Accessibility.Private)
{
// member is effectively private
}
}
```