Skip to content

Commit

Permalink
Use RuntimeHelpers.GetHashCode instead of obj.GetHashCode (dotnet#31756)
Browse files Browse the repository at this point in the history
* Use RuntimeHelpers.GetHashCode instead of obj.GetHashCode

* Fix unit test

* Code review fixes

* Code review fixes

* Update src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReferenceEqualsEqualityComparer.cs

Co-Authored-By: David Cantu <[email protected]>

Co-authored-by: David Cantu <[email protected]>
  • Loading branch information
Marusyk and jozkee authored Feb 6, 2020
1 parent 725968c commit c626d1a
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
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]);
}
}
}

0 comments on commit c626d1a

Please sign in to comment.