Static Code Analysis for C#: Rules, Roslyn, and Practical Examples

C# teams rely on static analysis to keep .NET codebases maintainable as they grow. Here is how C# static analysis works, what to look for, and how to fit scanning into your GitHub workflow.

Video explainer (1:31) · Watch with transcript

How C# static analysis works

Most C# analyzers use Roslyn — the .NET compiler platform — to parse syntax trees and run semantic analysis. IDE inspections, build-time analyzers, and repository scanners all build on this foundation.

Findings reference file paths, line numbers, rule IDs, and often include remediation guidance.

Common C# checks

  • Empty catch blocks and missing logging in error paths
  • Long methods and high cyclomatic complexity
  • Hardcoded passwords and connection strings
  • Async anti-patterns — blocking on Task.Result, Thread.Sleep in async code
  • Exception handling smells — throw ex instead of throw
  • SOLID heuristics — dependency inversion, single responsibility, and related design signals

Example: dependency construction

Direct instantiation of concrete services can reduce testability. Static analysis may flag this as a potential dependency inversion issue:

// Potential design issue — tight coupling
public class OrderService
{
    private readonly SqlOrderRepository _repo = new SqlOrderRepository();

    public Order Get(int id) => _repo.Find(id);
}

// Prefer injection for testability
public class OrderService
{
    private readonly IOrderRepository _repo;

    public OrderService(IOrderRepository repo) => _repo = repo;

    public Order Get(int id) => _repo.Find(id);
}

Roslyn analyzers vs repository scanners

Roslyn analyzers integrated into build pipelines catch issues at compile time — ideal for enforcing team standards on every commit.

Repository scanners like CodeInspector analyze the full GitHub project, rank findings by severity, track scan history, and provide recommendations in the Explorer workspace. Use both: analyzers for immediate feedback, repository scans for baseline audits and release checks.

GitHub workflow with CodeInspector

Connect GitHub or paste a public repository URL, run a scan, and review C# findings in the Explorer. Each issue includes context, a recommendation, and suggested code where available. Fix locally, commit, open a pull request, and re-scan to confirm improvements.

Pair scans with your existing PR review process — static analysis covers breadth; reviewers focus on business logic and API design.

Related