CodeQL documentation

Dereferenced variable may be null

ID: cs/dereferenced-value-may-be-null
Kind: path-problem
Severity: warning
Precision: high
Tags:
   - 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 may have a null value on some execution paths leading to the dereferencing, the dereferencing may result in a NullReferenceException.

Recommendation

Ensure that the variable does not have a null value when it is dereferenced.

Example

In the following example, the method DoPrint() dereferences its parameter o unconditionally, resulting in a NullReferenceException via the call DoPrint(null).

using System;

class Bad
{
    void DoPrint(object o)
    {
        Console.WriteLine(o.ToString());
    }

    void M()
    {
        DoPrint("Hello");
        DoPrint(null);
    }
}

In the revised example, the method DoPrint() guards the dereferencing with a null check.

using System;

class Good
{
    void DoPrint(object o)
    {
        if (o != null)
            Console.WriteLine(o.ToString());
    }

    void M()
    {
        DoPrint("Hello");
        DoPrint(null);
    }
}

References