views:

167

answers:

2

Following on from my question here, I'm trying to create a generic value equality comparer. I've never played with reflection before so not sure if I'm on the right track, but anyway I've got this idea so far:

bool ContainSameValues<T>(T t1, T t2)
{
    if (t1 is ValueType || t1 is string)
    {
        return t1.Equals(t2);
    }

    else 
    {
        IEnumerable<PropertyInfo> properties = t1.GetType().GetProperties().Where(p => p.CanRead);
        foreach (var property in properties)
        {
            var p1 = property.GetValue(t1, null);
            var p2 = property.GetValue(t2, null);

            if( !ContainSameValues<p1.GetType()>(p1, p2) )
                return false;
        }
    }
    return true;
}

This doesn't compile because I can't work out how to set the type of T in the recursive call. Is it possible to do this dynamically at all?

There are a couple of related questions on here which I have read but I couldn't follow them enough to work out how they might apply in my situation.

+2  A: 

You need to call the method using reflection, like this:

MethodInfo genericMethod = typeof(SomeClass).GetMethod("ContainSameValues");
MethodInfo specificMethod = genericMethod.MakeGenericMethod(p1.GetType());
if (!(bool)specificMethod.Invoke(this, new object[] { p1, p2 }))

However, your method should not be generic in the first place; it should simply take two object parameters. (Or, if it is generic, it should cache properties and delegates in a generic type)

SLaks
Btw you can improve the performance using Expression instead of Reflection.
Danny Chen
@Danny: But only if you cache the expression. (In a static field in a generic type) Also, you can get even better performance by creating a delegate.
SLaks
+1  A: 

You can avoid reflection on invocation if you are happy to compare based on the statically know types of the properties.

This relies on Expressions in 3.5 to do the one off reflection in a simple manner, it is possible to do this better to reduce effort for extremely nested types but this should be fine for most needs.

If you must work off the runtime types some level of reflection will be required (though this would be cheap if you again cache the per property access and comparison methods) but this is inherently much more complex since the runtime types on sub properties may not match so, for full generality you would have to consider rules like the following:

  • consider mismatched types to NOT be equal
    • simple to understand and easy to implement
    • not likely to be a useful operation
  • At the point the types diverge use the standard EqualityComparer<T>.Default implementation on the two and recurse no further
    • again simple, somewhat harder to implement.
  • consider equal if they have a common subset of properties which are themselves equal
    • complicated, not really terribly meaningful
  • consider equal if they share the same subset of properties (based on name and type) which are themselves equal
    • complicated, heading into Duck Typing

There are a variety of other options but this should be food for thought as to why full runtime analysis is hard.

(note that I have changed you 'leaf' termination guard to be what I consider to be superior, if you want to just use sting/value type for some reason feel free)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;


class StaticPropertyTypeRecursiveEquality<T>
{
    private static readonly Func<T,T, bool> actualEquals;

    static StaticPropertyTypeRecursiveEquality()
    {
        if (typeof(IEquatable<T>).IsAssignableFrom(typeof(T)) || 
            typeof(T).IsValueType ||
            typeof(T).Equals(typeof(object)))
        {
            actualEquals = 
                (t1,t2) => EqualityComparer<T>.Default.Equals(t1, t2);
        }
        else 
        {
            List<Func<T,T,bool>> recursionList = new List<Func<T,T,bool>>();
            var getterGeneric = 
                typeof(StaticPropertyTypeRecursiveEquality<T>)
                    .GetMethod("MakePropertyGetter", 
                        BindingFlags.NonPublic | BindingFlags.Static);
            IEnumerable<PropertyInfo> properties = typeof(T)
                .GetProperties()
                .Where(p => p.CanRead);
            foreach (var property in properties)                
            {
                var specific = getterGeneric
                    .MakeGenericMethod(property.PropertyType);
                var parameter = Expression.Parameter(typeof(T), "t");
                var getterExpression = Expression.Lambda(
                    Expression.MakeMemberAccess(parameter, property),
                    parameter);
                recursionList.Add((Func<T,T,bool>)specific.Invoke(
                    null, 
                    new object[] { getterExpression }));                    
            }
            actualEquals = (t1,t2) =>
                {
                    foreach (var p in recursionList)
                    {
                        if (t1 == null && t2 == null)
                            return true;
                        if (t1 == null || t2 == null)
                            return false;
                        if (!p(t1,t2))
                            return false;                            
                    }
                    return true;
                };
        }
    }

    private static Func<T,T,bool> MakePropertyGetter<TProperty>(
        Expression<Func<T,TProperty>> getValueExpression)
    {
        var getValue = getValueExpression.Compile();
        return (t1,t2) =>
            {
                return StaticPropertyTypeRecursiveEquality<TProperty>
                    .Equals(getValue(t1), getValue(t2));
            };
    }

    public static bool Equals(T t1, T t2)
    {
        return actualEquals(t1,t2);
    }
}

for testing I used the following:

public class Foo
{
    public int A { get; set; }
    public int B { get; set; }
}

public class Loop
{
    public int A { get; set; }
    public Loop B { get; set; }
}

public class Test
{
    static void Main(string[] args)
    {
        Console.WriteLine(StaticPropertyTypeRecursiveEquality<String>.Equals(
            "foo", "bar"));
        Console.WriteLine(StaticPropertyTypeRecursiveEquality<Foo>.Equals(
            new Foo() { A = 1, B = 2  },
            new Foo() { A = 1, B = 2 }));
        Console.WriteLine(StaticPropertyTypeRecursiveEquality<Loop>.Equals(
            new Loop() { A = 1, B = new Loop() { A = 3 } },
            new Loop() { A = 1, B = new Loop() { A = 3 } }));
        Console.ReadLine();
    }
}
ShuggyCoUk
thanks for a very detailed and infomative answer.
fearofawhackplanet