Make User implement IEquatable for more consistent comparisons

This commit is contained in:
Ruby Rose 2017-07-13 16:00:40 +03:00
parent 1cdd33a78a
commit 4216501c45

View file

@ -363,7 +363,7 @@ namespace TShockAPI.DB
}
/// <summary>A database user.</summary>
public class User
public class User : IEquatable<User>
{
/// <summary>The database ID of the user.</summary>
public int ID { get; set; }
@ -581,10 +581,66 @@ namespace TShockAPI.DB
return HashPassword(Encoding.UTF8.GetBytes(password));
}
}
#region IEquatable
/// <summary>UserManagerException - An exception generated by the user manager.</summary>
[Serializable]
/// <summary>Indicates whether the current <see cref="User"/> is equal to another <see cref="User"/>.</summary>
/// <returns>true if the <see cref="User"/> is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
/// <param name="other">An <see cref="User"/> to compare with this <see cref="User"/>.</param>
public bool Equals(User other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return ID == other.ID && string.Equals(Name, other.Name);
}
/// <summary>Indicates whether the current <see cref="User"/> is equal to another object.</summary>
/// <returns>true if the <see cref="User"/> is equal to the <paramref name="obj" /> parameter; otherwise, false.</returns>
/// <param name="obj">An <see cref="User"/> to compare with this <see cref="User"/>.</param>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((User)obj);
}
/// <summary>Serves as the hash function. </summary>
/// <returns>A hash code for the current <see cref="User"/>.</returns>
public override int GetHashCode()
{
unchecked
{
return (ID * 397) ^ (Name != null ? Name.GetHashCode() : 0);
}
}
/// <summary>
/// Compares equality of two <see cref="User"/> objects.
/// </summary>
/// <param name="left">Left hand of the comparison.</param>
/// <param name="right">Right hand of the comparison.</param>
/// <returns>true if the <see cref="User"/> objects are equal; otherwise, false.</returns>
public static bool operator ==(User left, User right)
{
return Equals(left, right);
}
/// <summary>
/// Compares equality of two <see cref="User"/> objects.
/// </summary>
/// <param name="left">Left hand of the comparison.</param>
/// <param name="right">Right hand of the comparison.</param>
/// <returns>true if the <see cref="User"/> objects aren't equal; otherwise, false.</returns>
public static bool operator !=(User left, User right)
{
return !Equals(left, right);
}
#endregion
}
/// <summary>UserManagerException - An exception generated by the user manager.</summary>
[Serializable]
public class UserManagerException : Exception
{
/// <summary>Creates a new UserManagerException object.</summary>