CodeQL documentation

Null argument to Equals(object)

ID: cs/null-argument-to-equals
Kind: problem
Security severity: 
Severity: warning
Precision: high
   - reliability
   - correctness
Query suites:
   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

It is common to want to check an object against null, but this should not be done using the Equals method. If the object really is null, a NullReferenceException is thrown when attempting to call Equals, with unexpected results.


The offending call should be replaced with either == or ReferenceEquals (the difference being that == can be overridden but ReferenceEquals cannot).


In the following example, IsNull will throw a NullReferenceException when o is null.

class Bad
    bool IsNull(object o) => o.Equals(null);

In the revised example, IsNull will correctly return true when o is null.

class Good
    bool IsNull(object o) => o == null;


  • © GitHub, Inc.
  • Terms
  • Privacy