Let's say I have this example:
public class Player
{
public string Username { get; set; }
private sealed class PlayerEqualityComparer : IEqualityComparer<Player>
{
public bool Equals(Player x, Player y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return x.Username == y.Username;
}
public int GetHashCode(Player obj)
{
return (obj.Username != null ? obj.Username.GetHashCode() : 0);
}
}
public static IEqualityComparer<Player> Comparer { get; } = new PlayerEqualityComparer();
}
I have a doubt about GetHashCode
: its returned value depends on the hash of Username
but we know that even if two strings contain the same value, their hash is computed by their reference, generating a different Hash.
Now if I have two Player
s like this:
Player player1 = new Player {Username = "John"};
Player player2 = new Player {Username = "John"};
By Equals
they're the same, but by GetHashCode
they are likely not. What happens when I use this PlayerEqualityComparer
in a Except
or Distinct
method then? Thank you