All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S1128.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

Unnecessary using directives refer to importing namespaces, types or creating aliases that are not used or referenced anywhere in the code.

Although they don’t affect the runtime behavior of the application after compilation, removing them will:

  • Improve the readability and maintainability of the code.
  • Help avoid potential naming conflicts.
  • Improve the build time, as the compiler has fewer lines to read and fewer types to resolve.
  • Reduce the number of items the code editor will show for auto-completion, thereby showing fewer irrelevant suggestions.

Starting with C# 10, it’s possible to define global usings for an entire project. They reduce the need for repetitive namespace inclusions, but can also mask which namespaces are truly necessary for the code at hand. Over-relying on them can lead to less transparent code dependencies, especially for newcomers to the project.

Exceptions

The rule will not raise a warning for global using directives, even if none of the types of that namespace are used in the project:

global using System.Net.Sockets; // Compliant by exception

Unnecessary using directives are ignored in ASP.NET Core projects in the following files:

  • _Imports.razor
  • _ViewImports.cshtml

How to fix it

While it’s not difficult to remove these unneeded lines manually, modern code editors support the removal of every unnecessary using directive with a single click from every file of the project.

Code examples

Noncompliant code example

using System.IO;
using System.Linq;
using System.Collections.Generic;   // Noncompliant - no types are used from this namespace
using MyApp.Helpers;                // Noncompliant - FileHelper is in the same namespace
using MyCustomNamespace;            // Noncompliant - no types are used from this namespace

namespace MyApp.Helpers
{
    public class FileHelper
    {
        public static string ReadFirstLine(string filePath) =>
            File.ReadAllLines(filePath).First();
    }
}

Compliant solution

using System.IO;
using System.Linq;

namespace MyApp.Helpers
{
    public class FileHelper
    {
        public static string ReadFirstLine(string filePath) =>
            File.ReadAllLines(filePath).First();
    }
}

Resources

Documentation

Related rules

  • {rule:csharpsquid:S1144} - Unused private types or members should be removed
  • {rule:csharpsquid:S1481} - Unused local variables should be removed




© 2015 - 2024 Weber Informatics LLC | Privacy Policy