user1144
user1144

Reputation:

Equality comparing objects

I have code like this:

 public bool AreSame(CreditProposal creditProposal)
    {
        if (!ContractingParty.Equals(creditProposal.ContractingParty))
            return false;
        if (!UltimateParent.Equals(creditProposal.UltimateParent))
            return false;
        if (!Rebound.Equals(creditProposal.Rebound))
            return false;
        if (!ContactPerson.Equals(creditProposal.ContactPerson))
            return false;
        if (!DateOfVisit.Equals(creditProposal.DateOfVisit))
            return false;
      .... and so on 10 more times

Is there a way to do this more concise? Or will that mean I get into reflection hell?

Upvotes: 2

Views: 101

Answers (2)

Paul Turner
Paul Turner

Reputation: 39615

The instinctive way to handle this situation is to override the Object.Equals(Object) method and implement IEquatable<T> for your type.

However, overriding Object.Equals will prompt you to also override Object.GetHashCode(), which is a lot harder to do correctly. Most notably, GetHashCode() must return the same value each time it is called on the same instance, and must return the same value for two objects which are considered equal. If your type is mutable, this becomes a real pain. (In fact, GetHashCode() is so difficult to implement correctly, there's a whole tag for it on StackOverflow: https://stackoverflow.com/questions/tagged/gethashcode)

The static implementation for Equals usually looks like this:

public static bool Equals(CreditProposal proposalA, CreditProposal proposalB)
{
    // Check whether both values are null.
    if(object.ReferenceEquals(proposalA, null) 
        && object.ReferenceEquals(proposalB, null))
    {
        return true;
    }

    // Check whether either value is null.
    if(object.ReferenceEquals(proposalA, null) 
        || object.ReferenceEquals(proposalB, null))
    {
        return false;
    }

    // Check whether hashcodes are different.
    if(proposalA.GetHashCode() != proposalB.GetHashCode())
    {
        return false;
    }

    // Check for value equality.
    return Party.Equals(
            proposalA.ContractingParty, 
            proposalB.ContractingParty)
        && ParentProposal.Equals(
            proposalA.UltimateParent, 
            proposalB.UltimateParent);
        // Add more conditions for equality here.
}

You would call this implementation from all your instance methods.

Upvotes: 2

Ken D
Ken D

Reputation: 5968

Override Equals method.

Check this on MSDN

And notice If you implement ==, you must implement !=.

Upvotes: 4

Related Questions