Monday 15 March 2010

.net - Is there a better way to implment Equals for object with lots of fields? -


See also

I have a lot of data transfer objects (DTOs) I have many simple fields in each I need to implement equivalent on all of them (so I can write some unit tests for some WCF transport for them).

The code I am using is:

  public override Bull equivalent (object rhs) {RequestArguments other = rhs as requested requests; Other Return! = Null & amp; Amp; other. M_RequestId.Equals (RequestId) & amp; Amp; other. M_type Eckels (M_type) & amp; Amp; other. MO Parameter. E.L. (M_Parameters) & amp; Amp; Other.m_user.Equals (m_user); }  

Should be a better way! ... (Listing all areas is asking for errors and maintenance problems)

Example We have the object to help with cloning () Clon () from membership, but I can not find anything to help with equals, we are in full faith, so a reflection based solution is an answer, but I do not want to change the wheel again. >

(Sorry, we domain-specific Do not generate DTO from language, otherwise this kind of thing will be easy! I am also unable to change the build system to add another step)

Funny you should ask, I recently published some code to do this. Check me to see if it meets your needs.

It is very easy to use and very efficient too. It uses the IL-Fest to run the entire equivalent and GetHashCode function for the first time (once for each type of use). This compares the object used by the default parity comparison for each item (private or public) compared to that type (equity compar. Default). We are using it for a while in production and it feels stable, but I will not give any guarantees =)

It takes care of all those edge-edge cases, you rarely When you think of rolling equal to your own method (i.e., you can not compare your object with taps unless you box it in an object and close too many blank-related issues. Give).

I mean to write a blog post about it, but it is not found around it yet the code is a bit undocumented, but if you like it, I can clean it a little bit .

  Public override int GetHashCode () {return MemberwiseEqualityComparer & lt; Foo & gt; .Default.GetHashCode (this); } Public override baul par (object obj) {if (obj == faucet) return false; Return equal (obj as fu); } Public Override Bull Iqlus (Fu Other) {Return Membership Features Consistency & lt; Foo & gt; Default. Ecloss (this, others); }  

MemberwiseEqualityComparer is issued under meaining, you can do anything you want to do with it, give it a little license to use it in proprietary solution Including without using.


No comments:

Post a Comment