New Record types do not allow overriding the equals method #4376
Answered
by
ufcpp
tmccowan
asked this question in
Language Ideas
Replies: 1 comment 1 reply
-
public record Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
public byte[] Data { get; init; }
// you can customize the equality by
public virtual bool Equals(Person other)
{
return other != null
&& FirstName == other.FirstName
&& LastName == other.LastName
&& new BigInteger(Data) == new BigInteger(other.Data);
}
public override int GetHashCode()
{
unchecked
{
const int HashingBase = (int)2166136261;
const int HashingMultiplier = 16777619;
int hash = HashingBase;
hash = (hash * HashingMultiplier) ^ FirstName.GetHashCode();
hash = (hash * HashingMultiplier) ^ LastName.GetHashCode();
hash = (hash * HashingMultiplier) ^ new BigInteger(Data).GetHashCode();
return hash;
}
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
tmccowan
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I started testing out record types in an application that I maintain and ran into some issues. The default == logic works just fine until you have a reference type property.
Here is an example of my problem
Person p1 = new() { FirstName = "Travis", LastName = "McCowan", Data = new byte[] { 1, 3, 5, 7, 9 } };
Person p2 = p1 with { Data = new byte[] { 1, 3, 5, 7, 9 } };
Console.WriteLine(p1 == p2); // False
public record Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
public byte[] Data { get; init; }
}
Possible solutions to this issue
Person p1 = new() { FirstName = "Travis", LastName = "McCowan", Data = new byte[] { 1, 3, 5, 7, 9 } };
Person p2 = p1 with { Data = new byte[] { 1, 3, 5, 7, 9 } };
Console.WriteLine(p1 == p2); //True
public record Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
public byte[] Data { get; init; }
public override int GetHashCode()
{
unchecked
{
const int HashingBase = (int)2166136261;
const int HashingMultiplier = 16777619;
int hash = HashingBase;
hash = (hash * HashingMultiplier) ^ FirstName.GetHashCode();
hash = (hash * HashingMultiplier) ^ LastName.GetHashCode();
hash = (hash * HashingMultiplier) ^ new BigInteger(Data).GetHashCode();
return hash;
}
}
}
Beta Was this translation helpful? Give feedback.
All reactions