Arash
Arash

Reputation: 4260

C# compiler issues a compile error when implementing == and != operators record definitions

I have a record per the following example:

public record MyData
{
   public string Id { get; set; }
   public string Code { get; set; }
   public string Description { get; set; }
   
   public bool operator ==(MyData d1, MyData d2)
   {
      return d1.Id == d2.Id;
   }

   public bool operator !=(MyData d1, MyData d2)
   {
      return d1.Id != d2.Id;
   }
}

This is the error message that I get and I'm not sure how to resolve it!

error CS0111: Type 'MyData' already defines a member called 'op_Equality' with the same parameter types.

When I convert record to class this issue is resolved but due to some reasons we have to keep using record. What's the solution to get rid of this compile problem?

Upvotes: 1

Views: 720

Answers (1)

cassandrad
cassandrad

Reputation: 3526

It is by design according to specs:

For records, the compiler generates the Equals method. In practice, the implementation of value equality in records is measurably faster

In class types, you could manually override equality methods and operators to achieve value equality, but developing and testing that code would be time-consuming and error-prone. Having this functionality built-in prevents bugs that would result from forgetting to update custom override code when properties or fields are added or changed.

That means that you should consider performance benefits in comparison to struct types which have the same equality semantics but have their own disadvantages, for example, in terms of boxing.

Tho if you want to have your own equality logic working with the operators, you could add public virtual bool Equals(T) and public override int GetHashCode(). The compiler generated equality operators are calling virtual bool Equals(T) inside, which is autogenerated and uses value equality if not overrided by the developer.

Upvotes: 1

Related Questions