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
 
Tags
    Impact
      Clean code attribute
        1. Locks should be released within the same method

           Bug
        2. A write lock should not be released when a read lock has been acquired and vice versa

           Bug
        3. Backslash should be avoided in route templates

           Bug
        4. Component parameter type should match the route parameter type constraint

           Bug
        5. [JSInvokable] attribute should only be used on public methods

           Bug
        6. Blazor query parameter type should be supported

           Bug
        7. Message template placeholders should be unique

           Bug
        8. Log message template should be syntactically correct

           Bug
        9. Blocks should not be synchronized on local variables

           Bug
        10. Regular expressions should be syntactically valid

           Bug
        11. Non-async "Task/Task<T>" methods should not return null

           Bug
        12. Calls to delegate's method "BeginInvoke" should be paired with calls to "EndInvoke"

           Bug
        13. "PartCreationPolicyAttribute" should be used with "ExportAttribute"

           Bug
        14. "Shared" parts should not be created with "new"

           Bug
        15. Getters and setters should access the expected fields

           Bug
        16. "ConstructorArgument" parameters should exist in constructors

           Bug
        17. Windows Forms entry points should be marked with STAThread

           Bug
        18. Classes should implement their "ExportAttribute" interfaces

           Bug
        19. Empty collections should not be accessed or iterated

           Bug
        20. Collection elements should not be replaced unconditionally

           Bug
        21. Exceptions should not be created without being thrown

           Bug
        22. Collection sizes and array length comparisons should make sense

           Bug
        23. Calculations should not overflow

           Bug
        24. Serialization event handlers should be implemented correctly

           Bug
        25. Deserialization methods should be provided for "OptionalField" members

           Bug
        26. All branches in a conditional structure should not have exactly the same implementation

           Bug
        27. Types should be defined in named namespaces

           Bug
        28. "Thread.Resume" and "Thread.Suspend" should not be used

           Bug
        29. Mutable, non-private fields should not be "readonly"

           Bug
        30. "SafeHandle.DangerousGetHandle" should not be called

           Bug
        31. Empty nullable value should not be accessed

           Bug
        32. Nullable type comparison should not be redundant

           Bug
        33. Methods with "Pure" attribute should return a value

           Bug
        34. One-way "OperationContract" methods should have "void" return type

           Bug
        35. Optional parameters should be passed to "base" calls

           Bug
        36. Type inheritance should not be recursive

           Bug
        37. "string.ToCharArray()" and "ReadOnlySpan<T>.ToArray()" should not be called redundantly

           Bug
        38. Classes should not have only "private" constructors

           Bug
        39. Right operands of shift operators should be integers

           Bug
        40. "base.Equals" should not be used to check for reference equality in "Equals" if "base" is not "object"

           Bug
        41. Date and time should not be used as a type for primary keys

           Bug
        42. Expressions used in "Debug.Assert" should not produce side effects

           Bug
        43. Caller information parameters should come at the end of the parameter list

           Bug
        44. Static fields should appear in the order they must be initialized

           Bug
        45. Classes directly extending "object" should not call "base" in "GetHashCode" or "Equals"

           Bug
        46. Anonymous delegates should not be used to unsubscribe from Events

           Bug
        47. Delegates should not be subtracted

           Bug
        48. "async" methods should not return "void"

           Bug
        49. "ThreadStatic" should not be used on non-static fields

           Bug
        50. "IDisposables" created in a "using" statement should not be returned

           Bug
        51. "ThreadStatic" fields should not be initialized

           Bug
        52. "Object.ReferenceEquals" should not be used for value types

           Bug
        53. Generic parameters not constrained to reference types should not be compared to "null"

           Bug
        54. Classes should "Dispose" of members from the classes' own "Dispose" methods

           Bug
        55. Property assignments should not be made for "readonly" fields not constrained to reference types

           Bug
        56. Classes with "IDisposable" members should implement "IDisposable"

           Bug
        57. "IDisposables" should be disposed

           Bug
        58. SQL keywords should be delimited by whitespace

           Bug
        59. Doubled prefix operators "!!" and "~~" should not be used

           Bug
        60. Non-existent operators like "=+" should not be used

           Bug
        61. "NaN" should not be used in comparisons

           Bug
        62. The length returned from a stream read should be checked

           Bug
        63. Conditionally executed code should be reachable

           Bug
        64. Shared resources should not be used for locking

           Bug
        65. Blocks should be synchronized on read-only fields

           Bug
        66. Flags enumerations should explicitly initialize all their members

           Bug
        67. "GetHashCode" should not reference mutable fields

           Bug
        68. Composite format strings should not lead to unexpected behavior at runtime

           Bug
        69. Null pointers should not be dereferenced

           Bug
        70. For-loop conditions should be true at least once

           Bug
        71. A "for" loop update clause should move the counter in the right direction

           Bug
        72. "ToString()" method should not return null

           Bug
        73. Locks should be released on all paths

           Bug
        74. Methods without side effects should not have their return values ignored

           Bug
        75. Loops and recursions should not be infinite

           Bug
        76. Results of integer division should not be assigned to floating point variables

           Bug
        77. Integral numbers should not be shifted by zero or more than their number of bits-1

           Bug
        78. Values should not be uselessly incremented

           Bug
        79. Collections should not be passed as arguments to their own methods

           Bug
        80. Related "if/else if" statements should not have the same condition

           Bug
        81. Objects should not be created to be dropped immediately without being used

           Bug
        82. Identical expressions should not be used on both sides of operators

           Bug
        83. Loops with at most one iteration should be refactored

           Bug
        84. Variables should not be self-assigned

           Bug
        85. Floating point numbers should not be tested for equality

           Bug
        86. Method parameters, caught exceptions and foreach variables' initial values should not be ignored

           Bug
        87. "Equals(Object)" and "GetHashCode()" should be overridden in pairs

           Bug
        88. Finalizers should not throw exceptions

           Bug

        Null pointers should not be dereferenced

        intentionality - logical
        reliability
        Bug
        • cwe
        • symbolic-execution

        Why is this an issue?

        How can I fix it?

        More Info

        Accessing a null value will always throw a NullReferenceException most likely causing an abrupt program termination.

        Such termination might expose sensitive information that a malicious third party could exploit to, for instance, bypass security measures.

        Exceptions

        In the following cases, the rule does not raise:

        Extensions Methods

        Calls to extension methods can still operate on null values.

        using System;
        using System.Text.RegularExpressions;
        
        public static class Program
        {
            public static string RemoveVowels(this string value)
            {
                if (value == null)
                {
                    return null;
                }
                return Regex.Replace(value, "[aeoui]*","", RegexOptions.IgnoreCase);
            }
        
            public static void Main()
            {
                Console.WriteLine(((string?)null).RemoveVowels());  // Compliant: 'RemoveVowels' is an extension method
            }
        }
        

        Unreachable code

        Unreachable code is not executed, thus null values will never be accessed.

        public void Method()
        {
            object o = null;
            if (false)
            {
                o.ToString();    // Compliant: code is unreachable
            }
        }
        

        Validated value by analysis attributes

        Nullable analysis attributes enable the developer to annotate methods with information about the null-state of its arguments. Thus, potential null values validated by one of the following attributes will not raise:

        • NotNullAttribute
        • NotNullWhenAttribute
        • DoesNotReturnAttribute
        • DoesNotReturnIfAttribute

        It is important to note those attributes are only available starting .NET Core 3. As a workaround, it is possible to define those attributes manually in a custom class:

        using System;
        
        public sealed class NotNullAttribute : Attribute { } // The alternative name 'ValidatedNotNullAttribute' is also supported
        
        public static class Guard
        {
            public static void NotNull<T>([NotNull] T value, string name) where T : class
            {
                if (value == null)
                {
                    throw new ArgumentNullException(name);
                }
            }
        }
        
        public static class Utils
        {
            public static string Normalize(string value)
            {
                Guard.NotNull(value, nameof(value)); // Will throw if value is null
                return value.ToUpper(); // Compliant: value is known to be not null here.
            }
        }
        

        Validated value by Debug.Assert

        A value validated with Debug.Assert to not be null is safe to access.

        using System.Diagnostics;
        
        public void Method(object myObject)
        {
            Debug.Assert(myObject != null);
            myObject.ToString(); // Compliant: 'myObject' is known to be not null here.
        }
        

        Validated value by IDE-specific attributes

        Like with null-analysis-attribute, potential null values validated by one of the following IDE-specific attributes will not raise

        Visual Studio
        • ValidatedNotNullAttribute (The attribute is interpreted the same as the NotNullAttribute)
        JetBrains Rider
        • NotNullAttribute
        • TerminatesProgramAttribute
          using System;
          using JetBrains.Annotations;
          
          public class Utils
          {
              [TerminatesProgram]
              public void TerminateProgram()
              {
                  Environment.FailFast("A catastrophic failure has occurred.")
              }
          
              public void TerminatesProgramIsRespected()
              {
                  object myObject = null;
                  TerminateProgram();
                  myObject.ToString(); // Compliant: unreachable
              }
          }
          

        Null forgiving operator

        Expression marked with the null forgiving operator

        public void Method()
        {
            object o = null;
            o!.ToString();    // Compliant: the null forgiving operator suppresses the nullable warning
        }
        
          Available In:
        • SonarQube CloudDetect issues in your GitHub, Azure DevOps Services, Bitbucket Cloud, GitLab repositories
        • 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