Epic Nobody
Epic Nobody

Reputation: 189

struggling to understand Equals()

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();
p1.SetScore(7);
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?

Upvotes: 2

Views: 139

Answers (2)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28718

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?

Upvotes: 4

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

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

Upvotes: 10

Related Questions