Search code examples
c#.netwarningssuppress-warnings

How to suppress "possible unintended reference comparison" warning?


I get a "possible unintended reference comparison" in this situation:

class Parent {
    class Child : IEquitable<Child> {
        private readonly int index;
        private readonly Parent parent;
        internal Child(Parent parent, int index) {
            this.parent = parent;
            this.index = index;
        }
        public override int GetHashCode() {
            return parent.GetHashCode()*31 + index.GetHashCode();
        }
        public override bool Equals(object obj) {
            Child other = obj as Child.
            return other != null && Equals(other);
        }
        public override bool Equals(Child other) {
            // The warning I get is on the next line:
            return parent == other.parent && index == other.index;
        }
    }
    ...
}

However, reference comparison is fully intentional in this situation, because I want Child objects of different parents to be considered unequal to each other. How do I tell the compiler about my intention, and suppress the warning?


Solution

  • Although you could use #pragma to suppress warning in this situation, using ReferenceEquals provides a better alternative:

    public override bool Equals(Child other) {
        return ReferenceEquals(parent, other.parent) && index == other.index;
    }
    

    In addition to silencing the warning, this option makes it clear to other programmers reading your code that reference comparison is not a mistake.