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

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

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

If a variable that is not supposed to change is not marked as const, it could be accidentally reassigned elsewhere in the code, leading to unexpected behavior and bugs that can be hard to track down.

By declaring a variable as const, you ensure that its value remains constant throughout the code. It also signals to other developers that this value is intended to remain constant. This can make the code easier to understand and maintain.

In some cases, using const can lead to performance improvements. The compiler might be able to make optimizations knowing that the value of a const variable will not change.

How to fix it

Mark the given variable with the const modifier.

Code examples

Noncompliant code example

public bool Seek(int[] input)
{
  var target = 32;  // Noncompliant
  foreach (int i in input)
  {
    if (i == target)
    {
      return true;
    }
  }
  return false;
}

Compliant solution

public bool Seek(int[] input)
{
  const int target = 32;
  foreach (int i in input)
  {
    if (i == target)
    {
      return true;
    }
  }
  return false;
}

Noncompliant code example

public class Sample
{
  public void Method()
  {
    var context = $"{nameof(Sample)}.{nameof(Method)}";  // Noncompliant (C# 10 and above only)
  }
}

Compliant solution

public class Sample
{
  public void Method()
  {
    const string context = $"{nameof(Sample)}.{nameof(Method)}";
  }
}

Resources

Documentation

  • Microsoft Learn - const




© 2015 - 2024 Weber Informatics LLC | Privacy Policy