lundi 11 juillet 2022

Determine whether a C# Record implements custom Equality comparison by reflection

Is it possible to know whether a Record type has a custom implementation of the Equals method using reflection?

For example, with the following code:

public sealed record A
{
    public long Id { get; init; }
}

public sealed record B
{
    public string Name { get; init; }

    public bool Equals(B other) => StringComparer.InvariantCultureIgnoreCase.Equals(this.Name, other.Name); 
    public override int GetHashCode() => StringComparer.InvariantCultureIgnoreCase.GetHashCode(this.Name);
}

I would like a method which could return:

HasCustomEqualityImplementation(typeof(A)); // false
HasCustomEqualityImplementation(typeof(B)); // true

It does not seem obvious, as the compiler automatically generates an Equals method for record A, and I didn't find a way to differentiate it from the explicit implementation from record B, but I may have missed something.





Aucun commentaire:

Enregistrer un commentaire