Resharper - generate equality members, including base class members

Is it possible to generate equality members for a class that will also include members from the base class?

For example, an abstract base class:

public abstract class MyBaseClass { public int Property1; } 

Another class:

 public class MyOtherClass: MyBaseClass { public int Property2 {get; set;} } 

If I auto-generate equality members using Resharper, I get equality based only on the MyOtherClass.Property2 property, not Property1 from its base class.

+7
source share
1 answer

First create equality checks in the base class, and then do it in the descendant.

In the descendant, the difference will be in the class public bool Equals(MyOtherClass other) .

Without equality checks in the base class:

 public bool Equals(MyOtherClass other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other.Property2 == Property2; } 

With equality checks in the base class:

 public bool Equals(MyOtherClass other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return base.Equals(other) && other.Property2 == Property2; } 

Note the added call to base.Equals(other) , which will thus be responsible for the properties of the base class.

Please note that if you do this the other way around, first add equality checks to the descendant, and then add them to the base class, then ReSharper will not work and retroactively changes the code in the descendant, you need to either restore it (delete + generate) or change the code manually.

+10
source

All Articles