All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S2995.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

In C#, the Object.ReferenceEquals method is used to compare two reference type variables. If you use this method to compare two value types, such as int, float, or bool you will not get the expected results because value type variables contain an instance of the type and not a reference to it.

Due to value type variables containing directly an instance of the type, they can’t have the same reference, and using Object.ReferenceEquals to compare them will always return false even if the compared variables have the same value.

How to fix it

When comparing value types, prefer using the Object.Equals.

Note that in the case of structure types, it is recommended to implement value equality. If not, {rule:csharpsquid:S3898} might raise.

Code examples

Noncompliant code example

using System;

struct MyStruct
{
    int valueA;
    int valueB;
}

static class MyClass
{
    public static void Method(MyStruct struct1, MyStruct struct2)
    {
        if (Object.ReferenceEquals(struct1, struct2)) // Noncompliant: this will be always false
        {
            // ...
        }
    }
}

Compliant solution

using System;

struct MyStruct : IEquatable<MyStruct>
{
    int valueA;
    int valueB;

    public bool Equals(MyStruct other) => valueA == other.valueA && valueB == other.valueB;

    public override bool Equals(object obj) => obj is MyStruct other && Equals(other);

    public override int GetHashCode() => HashCode.Combine(valueA, valueB);

    public static bool operator ==(MyStruct lhs, MyStruct rhs) => lhs.Equals(rhs);

    public static bool operator !=(MyStruct lhs, MyStruct rhs) => !(lhs == rhs);
}

static class MyClass
{
    public static void Method(MyStruct struct1, MyStruct struct2)
    {
        if (struct1.Equals(struct2)) // Compliant: value are compared
        {
            // ...
        }
    }
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy