When generating an GetHashCode() implementation for an anonymous class, Roslyn calculates the initial hash value based on the property names. For example, the class generated for
var x = new { Int = 42, Text = "42" };
will have the following GetHashCode() method:
public override in GetHashCode() { int hash = 339055328; hash = hash * -1521134295 + EqualityComparer<int>.Default.GetHashCode( Int ); hash = hash * -1521134295 + EqualityComparer<string>.Default.GetHashCode( Text ); return hash; }
But if we change the property names, the initial value will change:
var x = new { Int2 = 42, Text2 = "42" }; public override in GetHashCode() { int hash = 605502342; hash = hash * -1521134295 + EqualityComparer<int>.Default.GetHashCode( Int2 ); hash = hash * -1521134295 + EqualityComparer<string>.Default.GetHashCode( Text2 ); return hash; }
What is the reason for this behavior? Is there any problem with choosing a large [prime?] Number and using it for all anonymous classes?
source share