Search code examples
c#structrecordequality

Replacing the synthesized Equals() of C# record struct


In short:

Is there any way to provide my own Equals( object? ) method for a record struct instead of being stuck with the one automagically generated by the compiler?

Note:

This question has nothing to do with replacing the automatically generated MyRecord.Equals( MyRecord ) method, which is trivially doable; This question is specifically about replacing the MyRecord.Equals( Object? ) method inherited from Object, which is a whole different story.

Background:

If I want to override Equals( object? ) in plain old class and struct, I am free to do so; however, I cannot do it with record; the IDE says "Member with the same signature is already declared", while the compiler gives "error CS0111: Type 'Color' already defines a member called 'Equals' with the same parameter types".

A quick look at official Microsoft documentation here and here says that this is by design.

The Question:

Does anyone know any workaround to this?

(Besides just never using record and forfeiting all of its convenience.)


Solution

    1. Is there any way to provide my own `Equals(object?) method for a record struct instead of being stuck with the one automagically generated by the compiler?

      No, it is not, as the record structs spec says:

      The record struct includes a synthesized override equivalent to a method declared as follows:

      public override readonly bool Equals(object? obj);
      

      It is an error if the override is declared explicitly.

    2. Does anyone know any workaround to this?

      You can try looking into some assembly weaving with something like Fody, but as far as I understand this happens after compilation, so it will not cover all possible scenarios (i.e. would not work for the same assembly usage).

      Personally I would look into dumping the ObsoleteAttribute approach and trying to implement Roslyn analyzer which will handle the type mismatch problem you are trying to solve.