Condividi tramite


CA1804: Remove unused locals

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
RuleId CA1804
Category Microsoft.Performance
Breaking change Non-breaking

Cause

A method declares a local variable but does not use the variable except possibly as the recipient of an assignment statement. For analysis by this rule, the tested assembly must be built with debugging information and the associated program database (.pdb) file must be available.

Rule description

Unused local variables and unnecessary assignments increase the size of an assembly and decrease performance.

How to fix violations

To fix a violation of this rule, remove or use the local variable.

Note

The C# compiler removes unused local variables when the optimize option is enabled.

When to suppress warnings

Suppress a warning from this rule if the variable was compiler emitted. It is also safe to suppress a warning from this rule, or to disable the rule, if performance and code maintenance are not primary concerns.

Example

The following example shows several unused local variables.

Imports System
Imports System.Windows.Forms

Namespace PerformanceLibrary

   Public Class UnusedLocals

      Sub SomeMethod()
      
         Dim unusedInteger As Integer
         Dim unusedString As String = "hello"
         Dim unusedArray As String() = Environment.GetLogicalDrives()
         Dim unusedButton As New Button()

      End Sub

   End Class

End Namespace
using System;
using System.Windows.Forms;

namespace PerformanceLibrary
{
   public class UnusedLocals
   {
      public void SomeMethod()
      {
         int unusedInteger;
         string unusedString = "hello";
         string[] unusedArray = Environment.GetLogicalDrives();
         Button unusedButton = new Button();
      }
   }
}

CA1809: Avoid excessive locals

CA1811: Avoid uncalled private code

CA1812: Avoid uninstantiated internal classes

CA1801: Review unused parameters