Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use RuntimeHelpers.GetHashCode instead of obj.GetHashCode #31756

Merged
merged 6 commits into from
Feb 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace System.Text.Json.Serialization
{
Expand All @@ -21,7 +22,7 @@ bool IEqualityComparer<T>.Equals(T x, T y)

int IEqualityComparer<T>.GetHashCode(T obj)
{
return obj!.GetHashCode();
return RuntimeHelpers.GetHashCode(obj!);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -217,12 +217,12 @@ public static void CustomHashCode()
};

string json = JsonSerializer.Serialize(list, s_serializerOptionsPreserve);
Assert.Equal(@"{""$id"":""1"",""$values"":[{""$id"":""2""},{""$id"":""3""}]}", json);
Assert.Equal(@"{""$id"":""1"",""$values"":[{""$id"":""2""},{""$ref"":""2""}]}", json);

List<ClassIncorrectHashCode> listCopy = JsonSerializer.Deserialize<List<ClassIncorrectHashCode>>(json, s_serializerOptionsPreserve);
// When a GetHashCode method is implemented incorrectly, round-tripping breaks,
// that is a user error and this validates that we are always calling user's GetHashCode.
Assert.NotSame(listCopy[0], listCopy[1]);
// Make sure that our DefaultReferenceResolver calls the ReferenceEqualityComparer that implements RuntimeHelpers.GetHashCode, and never object.GetHashCode,
// otherwise objects would not be correctly identified when searching for them in the dictionary.
Assert.Same(listCopy[0], listCopy[1]);
}
}
}