Take the 2-minute tour ×

So as I understand it Equals() determines whether the specified object is equal to the current object.

So if i have this Player class:

public class Player
    int score;

    public object Clone()
        return this.MemberwiseClone(); 

    public void SetScore(int i)
        this.score = i; 

    public int GetScore()
        return this.score; 

Ant then I instantiate two Player's like this:

Player p1 = new Player();
Player p2 = (Player)p1.Clone(); 

Why is it that does Equals() return false when used like this:

Console.WriteLine(p1.Equals(p2)); // prints "False" to console

How are they not equal?

share|improve this question
add comment

2 Answers

up vote 10 down vote accepted

Because unless you override the Equals function, it is comparing the references to see if they are the same object.

See Implementing the Equals Method.

There are cases where you may get some reference, and want to see if it is a certain object. Say:

Player myFavorite = new Player();
//do stuff...
Player fastest = GetFastestPlayer();
if (myFavorite == fastest)
    // I'm happy
share|improve this answer
what good is comparing the references to see if they are the same object? –  Epic Nobody Nov 11 '11 at 2:52
@EpicNobody: It's really the only sensible way to implement .Equals() on System.Object, since that class otherwise knows nothing of classes which inherit from it. –  David Nov 11 '11 at 2:57
add comment

Jonathon Rienhart is correct - unless you override Equals then you're only checking instances, not values. It doesn't matter if the two objects are identical, if they aren't the same object then they are not equal. See also: I am the same person as myself, but I'm not the same person as my identical twin.

If you override the Equals operator you can define what constitutes equality - for example, you might want two Players to be consider equal if they have the same score.

public override bool Equals(Object obj) 
    var player = (Player)obj;

    if (player != null && player.score== this.score)
        return true;

    return false;

Normally, however, you wouldn't want these two players to be equal. Surely it's possible to have two players with the same score?

share|improve this answer
When implementing Equals, I would do var player = obj as Player; to avoid an InvalidCastException. –  Jim Schubert Nov 11 '11 at 3:05
@JimSchubert Good point. –  Kirk Broadhurst Nov 11 '11 at 3:06
add comment

Your Answer


