Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 837935
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T05:13:23+00:00 2026-05-15T05:13:23+00:00

Following on from my question here , I’m trying to create a generic value

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T05:13:24+00:00Added an answer on May 15, 2026 at 5:13 am

    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();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.