Monday, September 19, 2016

Deep Object Comparison

As I mentioned in my last post you can't compare reference types using the == operator because it compares the memory addresses not the values. So even with everything being the same two objects will never equal each other.

Below is some sample code that actually does a deep comparison of object to figure out if they are similar or not.

By deep I mean it will recursively follow all enumerations down to their lowest levels and compare them as well.

You might notice that there is no comparison to check the objects are the same type.  If you are not familiar with T it is a generic and forces the compiler to ensure objects are of the same type to be passed into this method.

You'll also notice that values are compared as strings but for my purposes and at least to get you started this is sufficient.

If there was data you wanted to return you could also modify the return type to be a response object with a bool to indicate if objects are the same and a list of which fields differed per your needs.

      public bool ObjectsAreSame(T a, T b)
        {
            bool result = true;
            var t = a.GetType();
            var properties = t.GetProperties();

            foreach (var p in properties)
            {
                if (typeof(IEnumerable).IsAssignableFrom(p.GetType()) || typeof(IEnumerable<>).IsAssignableFrom(p.GetType()))
                {
                    ObjectsAreSame(a.GetType().GetProperty(p.Name).GetValue(a, null), b.GetType().GetProperty(p.Name).GetValue(b, null));
                }
                else
                {
                    if (a.GetType().GetProperty(p.Name).GetValue(a, null) != null && a.GetType().GetProperty(p.Name).GetValue(b, null) != null)
                    {
                        if ((a.GetType().GetProperty(p.Name).GetValue(a, null).ToString()) != (b.GetType().GetProperty(p.Name).GetValue(b, null).ToString()))
                        {
                            result = false;
                            break;
                        }
                    }
                }
            }

            return result;
        }

No comments:

Post a Comment