Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resharper - generate equality members including base class members

Is it possible to generate equality members for a class, which would also include members from its base class?

For example - abstract base class:

public abstract class MyBaseClass
{
    public int Property1;
}

Other class:

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

If I autogenerate equality members with Resharper, I get equality based only on MyOtherClass.Property2 property and not also on Property1 from its base class.

like image 205
sventevit Avatar asked Feb 02 '11 14:02

sventevit


1 Answers

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

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

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;
}

Notice the added call to base.Equals(other), which thus becomes responsible for the properties in the base class.

Note that if you do it the other way around, you first add the equality checks to the descendant, and then add them to the base class, then ReSharper does not go and retroactively modifies the code in the descendant, you either have to regenerate it (delete+generate), or modify the code by hand.

like image 161
Lasse V. Karlsen Avatar answered Oct 01 '22 21:10

Lasse V. Karlsen