简体   繁体   中英

Override the equality operators with Equals()

I've been debugging an issue for quite some time and realize that it was coming from the usage of an == on a object where I should have used the object.Equals()

In order to prevent such issue, would like that the == operator calls the Object.Equals() that I have overridden.

Is that possible? The following code runs into a Stack-overflow exception...

public static bool operator ==(Portfolio a, Portfolio b)
{
    return a != null && a.Equals(b);
}

public static bool operator !=(Portfolio a, Portfolio b)
{
    return a != null && !a.Equals(b);
}

Thanks!

You're recursively calling the != operator from your != operator, hence the stack overflow. Use ReferenceEquals instead:

public static bool operator !=(Portfolio a, Portfolio b)
{
    return !object.ReferenceEquals(a, null) && !a.Equals(b);
}

That said, this code is flawed because it'll return false if a is null and b isn't. You should check both objects for null:

public static bool operator !=(Portfolio a, Portfolio b)
{
    if (object.ReferenceEquals(a, null))
    {
        return !object.ReferenceEquals(b, null);
    }

    return !a.Equals(b);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM