Reputation: 3498
Is there any possibility to tell the C# compiler that a deeply immutable record type (C# 9+) can shortcut its Equals
check by returning true
immediately, when the checked objects have the same reference?
With "deeply immutable record" I mean that all properties are immutable in any depth:
public record MyImmutableRecord {
public int MyProp { get; init; }
public IReadOnlyList<AlsoImmutable> MyList { get; init; }
}
The compiler automatically creates an Equals
method which checks all properties. From ILSpy:
public virtual bool Equals(MyImmutableRecord? other)
{
return (object)other != null
&& EqualityContract == other!.EqualityContract
&& EqualityComparer<int>.Default.Equals(MyProp, other!.MyProp)
&& ...
}
This could be speeded up enormously by checking for the reference first. When equal, we know for sure that the content is equal too. If not, we have to continue by checking the properties :
public virtual bool Equals(MyImmutableRecord? other) {
if (object.ReferenceEquals(this, other)
return true;
return ... // Like above
}
Any chance to tell the compiler that we have such a truely immutable object and using this trick? Or does anybody know if this is planned for the future? Otherwise I guess I'll have to write my own Equals
implementation for each immutable record?
Upvotes: 1
Views: 596
Reputation: 3498
The answer is very easy (thanks for the comments). Of course, two objects are always equal when their reference is is equal... Independent of their mutability. Probably I just came across this idea because immutable data structures encourage developers to reuse and share objects all over the code, much more than mutable classes do.
The question should have been:
Why does the auto-generated
Equals
method do not contain a check for reference equality first, before checking the members in detail?
I ask this in the csharplang project: https://github.com/dotnet/csharplang/discussions/4411
EDIT 2021-02-11: This is now on the roadmap for Visual Studio 16.10: https://github.com/dotnet/roslyn/issues/51136
Upvotes: 4