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

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

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

Methods and properties that don’t access instance data should be marked as static for the following reasons:

  • Clarity and Intent: Marking a method/property as static makes it clear that the method does not depend on instance data and can be called without creating an instance of the class. This improves the readability of the code by clearly conveying the member’s intended use.
  • Performance: Instance methods/properties in C# require an instance of the class to be called. This means that even if the it doesn’t use any instance data, the runtime still needs to pass a reference to the instance during the call. For static methods and properties, this overhead is avoided, leading to slightly better performance.
  • Memory Usage: Since instance methods implicitly carry a reference to the instance (the caller object), they can potentially prevent the garbage collector from collecting the instance whem it is not otherwise referenced. Static members do not carry this overhead, potentially reducing memory usage.
  • Testing: Static members can be easier to test since they do not require an instance of the class. This can simplify unit testing and reduce the amount of boilerplate code needed to set up tests.

Exceptions

Methods with the following names are excluded because they can’t be made static:

How to fix it

Code examples

Noncompliant code example

public class Utilities
{
    public int MagicNum // Noncompliant - only returns a constant value
    {
        get
        {
            return 42;
        }
    }

    private static string magicWord = "please";
    public string MagicWord  // Noncompliant - only accesses a static field
    {
        get
        {
            return magicWord;
        }
        set
        {
            magicWord = value;
        }
    }

    public int Sum(int a, int b)  // Noncompliant - doesn't access instance data, only the method parameters
    {
        return a + b;
    }
}

Compliant solution

public class Utilities
{
    public static int MagicNum
    {
        get
        {
            return 42;
        }
    }

    private static string magicWord = "please";
    public static string MagicWord
    {
        get
        {
            return magicWord;
        }
        set
        {
            magicWord = value;
        }
    }

    public static int Sum(int a, int b)
    {
        return a + b;
    }
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy