Skip to content

Instantly share code, notes, and snippets.

@Andrey2G
Last active November 12, 2022 21:26
Show Gist options
  • Save Andrey2G/bb272e27165b552e2a8a17f52050fb6f to your computer and use it in GitHub Desktop.
Save Andrey2G/bb272e27165b552e2a8a17f52050fb6f to your computer and use it in GitHub Desktop.
Overriding GetHashCode
public class MyValueObject:ValueObject<MyValueObject>
{
public int field1{get;}
public double field2{get;}
public string field3{get;}
public override int GetHashCode()
{
//don't forget to check fields for null
unchecked
{
int hash = (int) 2166136261;
hash = (hash * 16777619) ^ field1.GetHashCode();
hash = (hash * 16777619) ^ field2.GetHashCode();
hash = (hash * 16777619) ^ field3.GetHashCode();
return hash;
}
}
//***************
}
@Andrey2G
Copy link
Author

One more interesting link
Value Object https://github.com/vkhorikov/LegacyProjects/blob/master/ACL/src/PackageDeliveryNew/Common/ValueObject.cs
and then it's enough to override the method GetEqualityComponents() like this
protected override IEnumerable GetEqualityComponents()
{
yield return field1;
yield return field2;
yield return field3;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment