-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Description
Description
I don't know if it is a bug or the doc that doesn't make it obvious. If I create 2 anonymous objects in 2 assemblies, the equals is always false, but the obj1.ToString().Equals(obj2.ToString()) returns true.
After reading the doc multiple times, it may be the expected behaviour:
If two or more anonymous object initializers in an assembly specify a sequence of properties that are in the same order and that have the same names and types, the compiler treats the objects as instances of the same type. They share the same compiler-generated type information.
And several paragraphs below:
Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashCode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.
I think the same anonymous type should be more explicit especially when we are talking about comparison. It should at least said that it is required to be in the same assembly.
Reproduction Steps
I created an anonymous object to post a JSON via PostAsJsonAsync and in the test assembly with Moq I wanted to intercept the call with the right object.
Expected behavior
Anonymous objects should be equal if all their properties are equal regardless of the assembly it is created on.
Actual behavior
Comparison requires to be on the same assembly.
Regression?
No
Known Workarounds
Use string to do the comparison...
obj1.ToString().Equals(obj2.ToString())
Configuration
.Net 7, x64
Document Details
⚠ Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.
- ID: d1b30ebe-b640-449b-3602-9891a55794db
- Version Independent ID: dd937177-98f0-a797-d49b-29332aae0614
- Content: Anonymous Types - C#
- Content Source: docs/csharp/fundamentals/types/anonymous-types.md
- Product: dotnet-csharp
- Technology: csharp-fundamentals
- GitHub Login: @BillWagner
- Microsoft Alias: wiwagn