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?