I am searching for difference between operator (==) and the Equals() Method. Many resources say that operator (==) compares reference identity. What is actually reference identity?
Asked
Active
Viewed 761 times
0
-
2@Soleil-MathieuPrévot: string isn't a value type, it's a reference type. – Jon Skeet Dec 08 '20 at 14:58
-
== is not a reference (pointer) equality for value types (double, int, struct etc), only for reference types, when not overloaded. – Soleil Dec 08 '20 at 15:14
-
reference identity / equality is described here https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/equality-comparisons#reference-equality where objects (non-primitive) need to point to same instance. bonus - react: https://medium.com/@jvcjunior/reference-identity-in-javascript-react-performance-12a8354addad - js: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness - P.S: not sure why this was closed as duplicate of the other (these 2 questions are neither value nor referentially equivalent completely :p) – gawkface Sep 24 '21 at 23:23
1 Answers
0
In addition to duplicates, I post this answer because the question is more specialized of what I found.
In simple words: reference identity is memory address equality, as two variables points to the same content or not, like a postal address or a glass of water. Because references are hidden pointers to forget to manage them.
GC is also a layer above to facilitate the management of instances of objects in memory and forget to destroy/free those we don't use anymore.
Operator ==
can be overloaded to compare values instead of references, so there are on object
Equals()
and ReferenceEquals()
methods.
Here are some tutorials:
-
1`Equals()` can also be overriden (and probably should be if `==` is). `ReferenceEquals()` can not. – Corak Dec 08 '20 at 14:51
-
3Note that `==` can't be *overridden* (no operators can) - but it can be *overloaded*. – Jon Skeet Dec 08 '20 at 14:58
-
3Also note that .NET doesn't use reference counting, so the second half of your answer is misleading. – Jon Skeet Dec 08 '20 at 14:59
-
@JonSkeet Learn something today about the ref count, thanks. Answer corrected and updated. – Dec 08 '20 at 15:02
-
3@OlivierRogier: Java doesn't use reference counting either (at least not in common implementations, as far as I'm aware). – Jon Skeet Dec 08 '20 at 15:04