views:

556

answers:

5

I have these data transfer objects objects:

public class Report 
{
    public int Id { get; set; }
    public int ProjectId { get; set; }
    //and so on for many, many properties.
}

I don't want to write

public bool areEqual(Report a, Report b)
{
    if (a.Id != b.Id) return false;
    if (a.ProjectId != b.ProjectId) return false;
    //Repeat ad nauseum
    return true;
}

Is there a faster way to test if to object with only properties have the same values (something that doesn't require one line of code or one logical expression per property?)

Switching to structs is not an option.

+2  A: 

Unfortunately you are going to have to write the method to compare the field values. System.ValueType is built to use reflection and compare the field values of a struct but even this is unadvisable due to slow performance. The best thing to do is to override the Equals method and also implement the IEquatable<T> interface for a strongly typed Equals overload.

While you are at it, you might as well provide a good GetHashCode override as well to complement the Equals implementation. All of these steps are considered good practice.

Andrew Hare
+2  A: 

You can do that easily with reflection. See an example here.

Otávio Décio
+11  A: 

How about some reflection, perhaps using Expression.Compile() for performance? (note the static ctor here ensures we only compile it once per T):

using System;
using System.Linq.Expressions;

public class Report {
    public int Id { get; set; }
    public int ProjectId { get; set; }
    static void Main() {
        Report a = new Report { Id = 1, ProjectId = 13 },
            b = new Report { Id = 1, ProjectId = 13 },
            c = new Report { Id = 1, ProjectId = 12 };
        Console.WriteLine(PropertyCompare.Equal(a, b));
        Console.WriteLine(PropertyCompare.Equal(a, c));
    }
}
static class PropertyCompare {
    public static bool Equal<T>(T x, T y) {
        return Cache<T>.Compare(x, y);
    }
    static class Cache<T> {
        internal static readonly Func<T, T, bool> Compare;
        static Cache() {
            var props = typeof(T).GetProperties();
            if (props.Length == 0) {
                Compare = delegate { return true; };
                return;
            }
            var x = Expression.Parameter(typeof(T), "x");
            var y = Expression.Parameter(typeof(T), "y");

            Expression body = null;
            for (int i = 0; i < props.Length; i++) {
                var propEqual = Expression.Equal(
                    Expression.Property(x, props[i]),
                    Expression.Property(y, props[i]));
                if (body == null) {
                    body = propEqual;
                } else {
                    body = Expression.AndAlso(body, propEqual);
                }
            }
            Compare = Expression.Lambda<Func<T, T, bool>>(body, x, y)
                          .Compile();
        }
    }
}
Marc Gravell
Genius! Works like a charm.
MatthewMartin
Wow, that's really sweet. Much nicer that the pure reflection version.
Jonathan Allen
+1  A: 

You will need to use reflection to do this, please follow this link --> http://stackoverflow.com/questions/506096/comparing-object-properties-in-c

Bhaskar
+1  A: 

Originally answered at (question 1831747)

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.

public override int GetHashCode()
{
    return MemberwiseEqualityComparer<Foo>.Default.GetHashCode(this);
}

public override bool Equals(object obj)
{
    if (obj == null)
        return false;

    return Equals(obj as Foo);
}

public override bool Equals(Foo other)
{
    return MemberwiseEqualityComparer<Foo>.Default.Equals(this, other);
}

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.

Markus Olsson