dotnet / dotnet/docs

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

Open
#29,690 1 comment 0 reactions 0 assignees View on GitHub
:watch: Not Triaged dotnet-architecture/svc microservices/subsvc
Dominant language
No language data
Stars
4.8k
Forks
6.1k
Avg merge
15h 21m
Merged PRs (30d)
370

Description

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.*

* ID: 70b14bbb-dc66-f1a2-8b14-39ef3b4bde1d
* Version Independent ID: cf912666-9ad3-1673-8f69-6bf52c034ef9
* Content: [Implementing value objects](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/implement-value-objects)
* Content Source: [docs/architecture/microservices/microservice-ddd-cqrs-patterns/implement-value-objects.md](https://github.com/dotnet/docs/blob/main/docs/architecture/microservices/microservice-ddd-cqrs-patterns/implement-value-objects.md)
* Product: **dotnet-architecture**
* Technology: **microservices**
* GitHub Login: @nishanil
* Microsoft Alias: **nanil**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.