Skip to content

Anonymous type accros assembly #38353

@oli-unreal

Description

@oli-unreal

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions