Skip to content

bartoszluka/cs-analyzers

Repository files navigation

Unused variables analyzer

What is this?

This is a C# code analyzer to warn you about unused variables. You can add it to your project, run dotnet build and see the warnings.

Why?

This project was created specifically because the default behavior of the compiler skips over unused variables. You might say that that's not true, that you've seen unused variable warnings before.

Yes, it exists, but unfortunately it's pretty limited. Specifically, the right hand side must be a compile time constant.

So:

public void Foo()
{
    var x = "unused"; // this is detected
    var y = new System.Text.StringBuilder(); // this is NOT detected
}

So basically it only catches the simplest case. In other words: it's useless.

This project is meant to fix this.

How to use it?

There are 3 ways of installing and using this analyzer, depending on what type of project you're working on:

  • the simple, single project one
  • central package management with .props files
  • vendor in the package and link it with ProjectRefence

choose the approach that suits you best.

Add to a project

This project is on NuGet, so you can add it through dotnet CLI:

dotnet add package MissingAnalyzers

or add this to your .csproj file:

<ItemGroup>
  <PackageReference Include="MissingAnalyzers" Version="0.6.0" />
</ItemGroup>

Add to all projects

If you're using "central package version management" you can add this to the Directory.Packages.props file

<ItemGroup>
  <PackageVersion Include="MissingAnalyzers" Version="0.6.0" />
</ItemGroup>

and this to Directory.Build.props file

<ItemGroup>
  <PackageReference Include="MissingAnalyzers" />
</ItemGroup>

Vendor in and use ProjectReference

You can clone this project, modify it if you need to, and use it as a project reference locally. To do this, first clone the repo

git pull https://github.com/bartoszluka/cs-analyzers MissingAnalyzers

then add it to the .csproj:

<ItemGroup>
  <ProjectReference
    Include="/path/to/MissingAnalyzers/MissingAnalyzers.csproj"
    OutputItemType="Analyzer"
    ReferenceOutputAssembly="false"
  />
</ItemGroup>

What's next?

  • catch unused variables and report a compiler warning
  • publish the package on NuGet
  • fill AnalyzerReleases.Shipped.md (whatever those are)
  • maybe support versions older than net8.0? netstandard2.0 supported
  • fix a bug with shadowing names in lambdas
  • fix support for top-level statements
  • fix a bug in identity lambdas x => x
  • fix a bug where the explicitly ignored parameter _ gets reported
  • add tests
  • add another analyzer if I see another problem

About

C# analyzers

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages