I am using Resharper to automate overwriting of the Equals
method and the ==
operator. One of the methods the tool overwritten is GetHashCode
:
public override int GetHashCode()
{
unchecked
{
return (Id.GetHashCode() * 397) ^ (Name != null ? Name.GetHashCode() : 0);
}
}
What is the function of this method and what is its role in comparing objects in the .NET Framework ? What is the function of the reserved word unchecked
? Why multiply the value of HashCode
of property Id by 397? (The project is set to .NET Framework version 4.5.1 ).
Full class code:
public class Class1 : IEquatable<Class1>
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool Equals(Class1 other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Id.Equals(other.Id) && string.Equals(Name, other.Name);
}
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((Class1) obj);
}
public override int GetHashCode()
{
unchecked
{
return (Id.GetHashCode() * 397) ^ (Name != null ? Name.GetHashCode() : 0);
}
}
public static bool operator ==(Class1 left, Class1 right)
{
return Equals(left, right);
}
public static bool operator !=(Class1 left, Class1 right)
{
return !Equals(left, right);
}
}