S3897 is an unsafe suggestion in my opinion

41 views
Skip to first unread message

Mike Barry

unread,
Jun 7, 2017, 8:48:47 AM6/7/17
to SonarQube
Hi all,


I think it is an unsafe suggestion on it's surface if the class is not sealed. Especially as a major. The reason is fairly well described here: http://blog.mischel.com/2013/01/05/inheritance-and-iequatable-do-not-mix/


But the important quote: A class that implements IEquatable<T> is saying, “I know how to compare two instances of type T or any type derived from T for equality.” After all, if type B derives from A, then B is-a A. That’s what inheritance means! The problem with implementing IEquatable<T> on a non-sealed type is that a base class cannot know how to compare instances of derived types. Trying to implement IEquatable<T> on a non-sealed class ends up producing inconsistent results when comparing instances of derived types.

Here is an example.

class Base : IEquatable<Base> {
  bool Equals(Base b) => return true;
}

class A : Base, IEquatable<A> {
  bool Equals(A a) => return false;
}

class B : Base, IEquatable<B> {
  bool Equals(B b) => return false;
}

A a = new A();
B b = new B();

Console.WriteLine(a.Equals(b)); // This should obviously return false as they are different classes however because of the existance of Base:Equals(Base b) it will return true.

Thanks,
Mike

Amaury Leve

unread,
Jun 14, 2017, 10:42:09 AM6/14/17
to Mike Barry, SonarQube
Further discussion is going to be handled on the GitHub issue thread: https://github.com/SonarSource/sonar-csharp/issues/420

Cheers,
Amaury

--
You received this message because you are subscribed to the Google Groups "SonarQube" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sonarqube+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sonarqube/287a5ec1-6cea-4907-8db3-6f4b6aebc6c6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--

Amaury Levé | SonarSource

Software Developer - .Net Team

http://sonarsource.com


Are you using SonarLint in your IDE? 
Reply all
Reply to author
Forward
0 new messages