SonarSource Rules
  • Products

    In-IDE

    Code Quality and Security in your IDE with SonarQube Ide

    IDE extension that lets you fix coding issues before they exist!

    Discover SonarQube for IDE

    SaaS

    Code Quality and Security in the cloud with SonarQube Cloud

    Setup is effortless and analysis is automatic for most languages

    Discover SonarQube Cloud

    Self-Hosted

    Code Quality and Security Self-Hosted with SonarQube Server

    Fast, accurate analysis; enterprise scalability

    Discover SonarQube Server
  • SecretsSecrets
  • ABAPABAP
  • AnsibleAnsible
  • ApexApex
  • AzureResourceManagerAzureResourceManager
  • CC
  • C#C#
  • C++C++
  • CloudFormationCloudFormation
  • COBOLCOBOL
  • CSSCSS
  • DartDart
  • DockerDocker
  • FlexFlex
  • GitHub ActionsGitHub Actions
  • GoGo
  • HTMLHTML
  • JavaJava
  • JavaScriptJavaScript
  • JSONJSON
  • JCLJCL
  • KotlinKotlin
  • KubernetesKubernetes
  • Objective CObjective C
  • PHPPHP
  • PL/IPL/I
  • PL/SQLPL/SQL
  • PythonPython
  • RPGRPG
  • RubyRuby
  • RustRust
  • ScalaScala
  • SwiftSwift
  • TerraformTerraform
  • TextText
  • TypeScriptTypeScript
  • T-SQLT-SQL
  • VB.NETVB.NET
  • VB6VB6
  • XMLXML
  • YAMLYAML
C#

C# static code analysis

Unique rules to find Bugs, Vulnerabilities, Security Hotspots, and Code Smells in your C# code

  • All rules 493
  • Vulnerability46
  • Bug88
  • Security Hotspot24
  • Code Smell335

  • Quick Fix 61
Filtered: 57 rules found
pitfall
    Impact
      Clean code attribute
        1. Literal suffixes should be upper case

           Code Smell
        2. Use a format provider when parsing date and time

           Code Smell
        3. Use UTC when recording DateTime instants

           Code Smell
        4. Always set the "DateTimeKind" when creating new "DateTime" instances

           Code Smell
        5. "PartCreationPolicyAttribute" should be used with "ExportAttribute"

           Bug
        6. Secure random number generators should not output predictable values

           Vulnerability
        7. "Shared" parts should not be created with "new"

           Bug
        8. Getters and setters should access the expected fields

           Bug
        9. Events should have proper arguments

           Code Smell
        10. Members should not have conflicting transparency annotations

           Vulnerability
        11. Windows Forms entry points should be marked with STAThread

           Bug
        12. Native methods should be wrapped

           Code Smell
        13. Classes should implement their "ExportAttribute" interfaces

           Bug
        14. Overloads with a "CultureInfo" or an "IFormatProvider" parameter should be used

           Code Smell
        15. Literals should not be passed as localized parameters

           Code Smell
        16. Operators should be overloaded consistently

           Code Smell
        17. Strings should be normalized to uppercase

           Code Smell
        18. Interface methods should be callable by derived types

           Code Smell
        19. Classes implementing "IEquatable<T>" should be sealed

           Code Smell
        20. Child class fields should not differ from parent class fields only by capitalization

           Code Smell
        21. Base class methods should not be hidden

           Code Smell
        22. Inherited member visibility should not be decreased

           Code Smell
        23. Threads should not lock on objects with weak identity

           Code Smell
        24. Objects should not be disposed more than once

           Code Smell
        25. "ISerializable" should be implemented correctly

           Code Smell
        26. Assemblies should have version information

           Code Smell
        27. "IDisposable" should be implemented correctly

           Code Smell
        28. Exceptions should not be thrown from unexpected methods

           Code Smell
        29. "operator==" should not be overloaded on reference types

           Code Smell
        30. Parameters with "[DefaultParameterValue]" attributes should also be marked "[Optional]"

           Code Smell
        31. "[Optional]" should not be used on "ref" or "out" parameters

           Code Smell
        32. Method overloads with default parameter values should not overlap

           Code Smell
        33. "value" contextual keyword should be used

           Code Smell
        34. Method calls should not resolve ambiguously to overloads with "params"

           Code Smell
        35. Inner class members should not shadow outer class "static" or type members

           Code Smell
        36. Methods named "Dispose" should implement "IDisposable.Dispose"

           Code Smell
        37. Conditionally executed code should be reachable

           Bug
        38. Whitespace and control characters in string literals should be explicit

           Code Smell
        39. Write-only properties should not be used

           Code Smell
        40. Public methods should not have multidimensional array parameters

           Code Smell
        41. Optional parameters should not be used

           Code Smell
        42. Fields should be private

           Code Smell
        43. Public constant members should not be used

           Code Smell
        44. Array covariance should not be used

           Code Smell
        45. Methods and properties that don't access instance data should be static

           Code Smell
        46. "async" and "await" should not be used as identifiers

           Code Smell
        47. Non-constant static fields should not be visible

           Code Smell
        48. Classes named like "Exception" should extend "Exception" or a subclass

           Code Smell
        49. Boolean checks should not be inverted

           Code Smell
        50. Related "if/else if" statements should not have the same condition

           Bug
        51. "switch" statements should not be nested

           Code Smell
        52. Constructors should only call non-overridable methods

           Code Smell
        53. Private fields only used as local variables in methods should become local variables

           Code Smell
        54. "for" loop stop conditions should be invariant

           Code Smell
        55. Control structures should use curly braces

           Code Smell
        56. Local variables should not shadow class fields or properties

           Code Smell
        57. Method overrides should not change parameter defaults

           Code Smell

        Non-constant static fields should not be visible

        consistency - conventional
        maintainability
        Code Smell
        • pitfall

        Why is this an issue?

        More Info

        Unlike instance fields, which can only be accessed by code having a hold on the instance, static fields can be accessed by any code having visibility of the field and its type.

        public class Math
        {
            public static double Pi = 3.14;  // Noncompliant
        }
        
        // Somewhere else, where Math and Math.Pi are visible
        var pi = Math.Pi; // Reading the value
        Math.Pi = 3.1416; // Mutating the value
        

        Another typical scenario of the use of a non-private mutable static field is the following:

        public class Shape
        {
            public static Shape Empty = new EmptyShape();  // Noncompliant
        
            private class EmptyShape : Shape
            {
            }
        }
        

        Non-private static fields that are neither const nor readonly, like the ones in the examples above, can lead to errors and unpredictable behavior.

        This can happen because:

        • Any object can modify these fields and alter the global state. This makes the code more difficult to read, debug and test.
          class Counters
          {
              public static int ErrorCounter = 0;
          }
          
          class Program
          {
              public static void Thread1()
              {
                  // ...
                  Counters.ErrorCounter = 0; // Error counter reset
                  // ...
              }
          
              public static void Thread2()
              {
                  // ...
                  if (Counters.ErrorCounter > 0)
                  {
                      Trace.TraceError($"There are {Counters.ErrorCounter} errors"); // It may print "There are 0 errors"
                  }
                  // ...
              }
          }
          
        • Correctly accessing these fields from different threads needs synchronization with lock or equivalent mechanisms. Improper synchronization may lead to unexpected results.
          class Counters
          {
              public static volatile int ErrorCounter;
          }
          
          class Program
          {
              public static void ImproperSynchronization()
              {
                  Counters.ErrorCounter = 0;
                  Parallel.ForEach(Enumerable.Range(0, 1000), _ => Counters.ErrorCounter++); // Volatile is not enough
                  Console.WriteLine(Counters.ErrorCounter); // May print less than 1000
              }
          
              public static void ProperSynchronization()
              {
                  Counters.ErrorCounter = 0;
                  Parallel.ForEach(Enumerable.Range(0, 1000), _ => Interlocked.Increment(ref Counters.ErrorCounter));
                  Console.WriteLine(Counters.ErrorCounter); // Always prints 1000
              }
          }
          

        Publicly visible static fields should only be used to store shared data that does not change. To enforce this intent, these fields should be marked readonly or converted to const.

        public class Math
        {
            public const double Pi = 3.14;
        }
        
        public class Shape
        {
            public static readonly Shape Empty = new EmptyShape();
        
            private class EmptyShape : Shape
            {
            }
        }
        
          Available In:
        • SonarQube IdeCatch issues on the fly,
          in your IDE
        • SonarQube CloudDetect issues in your GitHub, Azure DevOps Services, Bitbucket Cloud, GitLab repositories
        • SonarQube Community BuildAnalyze code in your
          on-premise CI
          Available Since
          9.1
        • SonarQube ServerAnalyze code in your
          on-premise CI
          Developer Edition
          Available Since
          9.1

        © 2008-2025 SonarSource SA. All rights reserved.

        Privacy Policy | Cookie Policy | Terms of Use