see also Hows to quick check if data
transfer two objects have equal
properties in C#?
I have lot of Data Transfer Objects (DTO) that each contains lots of simple fields. I need to implement Equals on all of them (so I can write some unit tests off transporting them var WCF).
The code I am using is:
public override bool Equals(object rhs)
{
RequestArguments other = rhs as RequestArguments;
return
other != null &&
other.m_RequestId.Equals(RequestId) &&
other.m_Type.Equals(m_Type) &&
other.m_Parameters.Equals(m_Parameters) &&
other.m_user.Equals(m_user);
}
There must be a better way!… (listing all the fields is rather asking for errors and maintenance problems)
E.g. we have Object. MemberwiseClone() to help with the Cloning() case, but I cannot find anything to help with Equals.
We are running in full trust so a reflection based solution is one answer, but I rather not reinvent the wheel.
(Sorry we don’t generate the DTO from a domain-specific language otherwise this sort of thing would be easy! Also I am not able to change the build system to add another step)
Funny you should ask, I recently published some code for doing exactly that. Check out my MemberwiseEqualityComparer to see if it fits your needs.
It’s really easy to use and quite efficient too. It uses IL-emit to generate the entire Equals and GetHashCode function on the first run (once for each type used). It will compare each field (private or public) of the given object using the default equality comparer for that type (EqualityComparer.Default). We’ve been using it in production for a while and it seems stable but I’ll leave no guarantees =)
It takes care of all those pescy edge-cases that you rarely think of when you’re rolling your own equals method (ie, you can’t comparer your own object with null unless you’ve boxed it in an object first and lot’s off more null-related issues).
I’ve been meaning to write a blog post about it but haven’t gotten around to it yet. The code is a bit undocumented but if you like it I could clean it up a bit.
The MemberwiseEqualityComparer is released under the MIT license meaining you can do pretty much whatever you want with it, including using it in proprietary solutions without changing you licensing a bit.