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

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

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

readonly fields can only be assigned in a class constructor. If a class has a field that’s not marked readonly but is only set in the constructor, it could cause confusion about the field’s intended use. To avoid confusion, such fields should be marked readonly to make their intended use explicit, and to prevent future maintainers from inadvertently changing their use.

Exceptions

  • Fields declared in classes marked with the Serializable attribute.
  • Fields declared in partial classes.
  • Fields with attributes are ignored.
  • Fields of type struct that are not primitive or pointer types are also ignored because of possible unwanted behavior.

How to fix it

Mark the given field with the readonly modifier.

Code examples

Noncompliant code example

public class Person
{
    private int _birthYear; // Noncompliant

    Person(int birthYear)
    {
        _birthYear = birthYear;
    }
}

Compliant solution

public class Person
{
    private readonly int _birthYear;

    Person(int birthYear)
    {
        _birthYear = birthYear;
    }
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy