Dereferenced variable is always null¶
ID: cs/dereferenced-value-is-always-null
Kind: problem
Security severity: 
Severity: error
Precision: very-high
Tags:
   - quality
   - reliability
   - correctness
   - exceptions
   - external/cwe/cwe-476
Query suites:
   - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
If a variable is dereferenced, for example as the qualifier in a method call, and the variable has a null value on all possible execution paths leading to the dereferencing, the dereferencing is guaranteed to result in a NullReferenceException.
Recommendation¶
Ensure that the variable does not have a null value when it is dereferenced.
Example¶
In the following examples, the condition s.Length > 0 is only executed if s is null.
using System;
namespace NullAlways
{
    class Bad
    {
        void DoPrint(string s)
        {
            if (s != null || s.Length > 0)
                Console.WriteLine(s);
        }
    }
}
In the revised example, the condition is guarded correctly by using && instead of ||.
using System;
namespace NullAlways
{
    class Good
    {
        void DoPrint(string s)
        {
            if (s != null && s.Length > 0)
                Console.WriteLine(s);
        }
    }
}
References¶
Microsoft, NullReferenceException Class.
Common Weakness Enumeration: CWE-476.