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 Players 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
Of course it is guaranteed that two strings with the same "value" have the same hashcode, otherwise
string.GetHashCodewas broken and someone would have noticed it already.I don't understand what you mean here, but it's wrong. The hashcode is derived from the string itself, so the "value". The documentation states:
In general following must apply:
GetHashCodemethod must return the same value.GetHashCodemethod does not have to return different values (but usually they are different, it's just not so important)