CodeQL documentation

Call to ReferenceEquals(…) on value type expressions

ID: cs/reference-equality-on-valuetypes
Kind: problem
Security severity: 
Severity: error
Precision: high
   - reliability
   - correctness
   - external/cwe/cwe-595
Query suites:
   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

The Object.ReferenceEquals(...) method is used to determine if two objects are the same instance. Since the method takes two objects as parameters, value types will automatically be boxed in different objects when calling the method. Hence, the method ReferenceEquals(..) will always return false when comparing value type expressions, including struct values. As such, this kind of check is at best useless and at worst erroneous.


Consider whether the equality test is needed. If it is not then remove it, otherwise replace it with a more appropriate equality check such as ==.


In this example, the programmer is attempting to compare two ints but since they are value types the ReferenceEquals method will always return false. They should really be compared using i == j.

class ReferenceEqualsOnValueTypes
    static void Main(string[] args)
        int i = 17;
        int j = 17;

        bool b = ReferenceEquals(i, j);


  • © GitHub, Inc.
  • Terms
  • Privacy