Fody / Equals

Generate Equals, GetHashCode and operators methods from properties.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

support Equality for derived class

opened this issue · comments

I've been straggling 'while using Fody-Equal with class inheritance. I would like to achieve an equality between 2 DerivedClass objects by comparing only their own properties without the BaseClass properties please see the following snippet:

namespace TestingFodyEqual
{
public class BaseClass
{
static void Main(string[] args)
{
DerivedClass d1 = new DerivedClass { CompareMeBy = 3 };
DerivedClass d2 = new DerivedClass { CompareMeBy = 3 };
if (d1 == d2)
{
Console.WriteLine("YEah");
}
}
public int Number1 { get; } = 5;
public int Number2 { get; } = 4;
}
[Equals(TypeCheck = TypeCheck.EqualsOrSubtype)]
class DerivedClass:BaseClass
{
public int CompareMeBy { get; set; } }
}

I expect for if(d1==d2) comparison to pass (due to the enum passed to the EqualAttribute), but after looking at the compiled code, I see it still compares 2 DerivedClass objects using all properties (thus of the base class and itself)

[GeneratedCode("Equals.Fody", "1.4.10.0"), DebuggerNonUserCode]
private static bool EqualsInternal(DerivedClass left, DerivedClass right)
{
//from here is unwanted
return left.CompareMeBy == right.CompareMeBy && left.Number1 == right.Number1 && left.Number2 == right.Number2;
}

do you have any suggestions?

I added possibility to skip base class properties(It is ready in 1.5.0).
Add attribute to your class like this:

[Equals(IgnoreBaseClassProperties`= = true)]
public DerivedClass:BaseClass
{...}

Please let me know if this suits you.