Saturday, November 5, 2016

Generic Object Comparer

Object.Equals, IEqualalityComparer are actually not generic and the latter only used in Collection or LINQ like Contains.

This ObjectComparer is T, but does not consider reference type property.
The ignore will eliminate reference type and also those properties not to be considered in equality by users. so more flexible than Equals

    class ObjectComparer
    {
        public static bool PublicInstancePropertiesEquals<T>( T self, T to, params string[] ignore) where T : class
        {
            if (self != null && to != null)
            {
                var type = typeof(T);
                var ignoreList = new List<string>(ignore);
                var allProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (var p in allProperties)
                {
                    if (!ignoreList.Contains(p.Name))
                    {
                        var selfValue = type.GetProperty(p.Name).GetValue(self, null);
                        var toValue = type.GetProperty(p.Name).GetValue(to, null);

                        if ((selfValue==null && toValue!=null) || (selfValue != null && !selfValue.Equals(toValue)))
                        {
                            return false;
                        }
                    }
                }
                return true;
            }
            return self == to;
        }
    }

No comments:

Post a Comment