Can 2 object point to the same item in memory but have different states?
This misunderstands the difference between an object and a variable or reference. The "item in memory" is the object, and the "state" it's talking about is the memory used to hold object. You refer to the object with a variable. The correct way to ask this question is below (and the difference does matter, as it's key to understanding a lot about how C# and similar languages work):
Can two variables refer to the same object in memory but have different states?
To answer this, you can have two variables refer to the same object in memory... but then it really is the same object. There's only one item in memory (it's the object), and that means only one state.
But that brings us to this question:
why override Equals?
You override the Equals()
method because sometimes you have two variables refer to two different objects, where those two objects have the same value. For example, I can create two string objects like this:
string a = "hello world";
string b = "hello world";
Ignoring string interning for the moment, those two variables refer to two different string objects in memory. The base Equals()
implementation inherited from Object
would result in false
, but the string type overloads the Equals()
method to do a value comparison, so instead a.Equals(b)
will result in true
.
And, finally, we know enough to answer this question:
Is it possible for two different objects stored in two different locations to still refer to same Entity?
Yes, it is. This, again, is why we overload the Equals()
method (along with GetHashCode()
). The base Equals()
method inherited from Object
would see those as two different objects, and the result would be false
. You override Equals()
for the type so it can return true
instead when the two objects represent the same value.
Now it starts to get tricky. An application might end up with two instances of an Employee type for the same person, where a user then changes the e-mail address property on just one of them. Now you have two instances. For the same employee. Where some fields have different values.
What do you want Equals()
to do? Think carefully about this; it has been the source for many bugs in many applications over the years. Sometimes you need it one way. Sometimes you need it the other. Sometimes the behavior needs to change depending on context within the same application.