Aug
13
2008

ReSharper Tip of the Day: Generate Equals

We’ve all probably had really basic POCO classes like this:

public class Fooberry
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

…and we’ve probably had to override Equals on them. When I went to go do it this last time, I saw ReSharper was trying to help me out.

So I expanded the context icon to see what it would do for me. It turns out it does something really cool.

It will complete the Equals statement for me! Awesome! I hate writing that method over and over.

Yes…I would like to compare those items…and we’re done!

public override bool Equals(object obj) {
    if (ReferenceEquals(null, obj)) return false;
    if (ReferenceEquals(this, obj)) return true;
    if (obj.GetType() != typeof (Fooberry)) return false;
    return Equals((Fooberry) obj);
}

public bool Equals(Fooberry obj)
{
    if (ReferenceEquals(null, obj)) return false;
    if (ReferenceEquals(this, obj)) return true;
    return Equals(obj.Foo, Foo) && Equals(obj.Bar, Bar);
}

public override int GetHashCode()
{
    unchecked
    {
        return ((Foo != null ? Foo.GetHashCode() : 0)*397) ^ (Bar != null ? Bar.GetHashCode() : 0);
    }
}

Pretty awesome if you ask me! The only downside is if I add new members to the class, I need to either add the tests in manually or generate the whole thing.

Steve (a co-worker)’s sharp eye noticed the unchecked keyword, and neither of us has used it so after looking it up it avoids overflow checks and trunks anything that would exceed normal bounds.

Written by mark in: ReSharper Tip of the Day | Tags: ,

No Comments »

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress | Kredit | TheBuckmaker