dotnet / docs

This repository contains .NET Documentation.
https://learn.microsoft.com/dotnet
Creative Commons Attribution 4.0 International
4.27k stars 5.9k forks source link

GetHashCode issue for ValueObjects with two equality components of the same type. #29690

Open walshy12345 opened 2 years ago

walshy12345 commented 2 years ago

Hi,

I've been helping teach programmers the benefits of ValueObjects; the example we were using led us to create ValueObjects for the 2-dimensional cartesian coordinate system with only integers as positions.

public sealed class Position : ValueObject
{
     public int X {get;}
     public int Y {get;}
}

Where X and Y would be the EqualityComponents.

There is an issue with the GetHashCode method since the exclusive OR would give the same HashCode for (1,1), and (2,2) (in fact, any point where X = Y). That HashCode would be 0. This issue only affects ValueObjects with at least two equality components of the same type; as their hashcodes could cancel each other.

I corrected this issue by using the following method, is it a viable fix? And should this fix be applied to all future ValueObjects?

public override int GetHashCode()
{
    return GetEqualityComponents()
                   .Select(x => x != null ? x.GetHashCode() : 0)
                   .Aggregate((x, y) => HashCode.Combine(x,y));
}

Regards, Adam


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

erjain commented 2 years ago

Hi @walshy12345, thanks for posting your query and taking the initiative to test it out. We are happy to review and accept a PR from you or the community users on this. In the future, we can recommend the fix accordingly.