What is the best way to implement GetHashCode() for class with lots of properties?

Spend the money to get a tool like Resharper, then just do Alt+Ins then E. This will bring up the "Generate Equality Members" dialog

enter image description here

From there just check the 100 boxes you need and it will autogenerate the GetHashCode() and Equals() functions for you

enter image description here
(the above took about 10 seconds to create)

Resharper does so much more too that it makes it worth the $150 for a personal license (you can use a personal license for work related activities without violating it, I checked). And if you are not making enough money as a programmer to afford a one time investment of $150 you really should start looking elsewhere to work as you are being very underpaid. (If you don't make any money as a programmer as you are working on a open source project Resharper is free for development teams of open source projects)


Calculate hashcode on all property values:

public override int GetHashCode()
{
    int hashCode = this.GetHashCodeOnProperties();
    return hashCode;
}

Define this extension method (which is reusable):

public static class HashCodeByPropertyExtensions
{
    public static int GetHashCodeOnProperties<T>(this T inspect)
    {
        return inspect.GetType().GetProperties().Select(o => o.GetValue(inspect)).GetListHashCode();
    }

    public static int GetListHashCode<T>(this IEnumerable<T> sequence)
    {
        return sequence
            .Where(item => item != null)
            .Select(item => item.GetHashCode())
            .Aggregate((total, nextCode) => total ^ nextCode);
    }
}

Might use this as well.. Just the overhead being a new instance of everytime you call GetHash().

new { A = Prop1, B = Prop2, C = Prop3, D = Prop4 }.GetHashCode();

Tags:

C#

Hashcode