59 lines
1.5 KiB
Plaintext
59 lines
1.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
The use of `==` to compare two objects is expected to do a reference comparison. That is, it is expected to return `true` if and only if they are the same object instance. Overloading the operator to do anything else will inevitably lead to the introduction of bugs by callers.
|
|
|
|
[source,csharp]
|
|
----
|
|
public static bool operator ==(MyType x, MyType y) // Noncompliant: confusing for the caller
|
|
{
|
|
// custom implementation
|
|
}
|
|
----
|
|
|
|
On the other hand, overloading it to do exactly that is pointless; that's what `==` does by default.
|
|
|
|
[source,csharp]
|
|
----
|
|
public static bool operator ==(MyType x, MyType y) // Noncompliant: redundant
|
|
{
|
|
if (x == null)
|
|
{
|
|
return y == null;
|
|
}
|
|
|
|
return object.ReferenceEquals(x,y);
|
|
}
|
|
----
|
|
|
|
=== Exceptions
|
|
|
|
* Classes with overloaded `operator +` or `operator -` are ignored.
|
|
* Classes that implement `IComparable<T>` or `IEquatable<T>` most probably behave as value-type objects and are ignored.
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types[Reference types]
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/equality-operators[Equality operators]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Remove this overload of "==".
|
|
|
|
=== Highlighting
|
|
|
|
`==`
|
|
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|