CodeQL documentation

Null argument to Equals(object)

ID: cs/null-argument-to-equals
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - quality
   - 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.

Recommendation

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

Example

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;
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy