mardi 1 septembre 2020

C# with object types the method Object.Equals (object a, object b) returns the wrong result

I need to check the object (not all properties), with primitive types everything works correctly, but with object types the method Object.Equals(object a, object b) returns the wrong result.

        public static bool IsModified<T>(T newProp, T oldProp) where T : class
    {
        List<string> IgnoreProps = new List<string> { "UpdatedOn", "UpdatedById", "UpdatedBy", "RowVersion" };

        Type type = typeof(T);
        foreach(PropertyInfo prop in type.GetProperties())
        {
            if (IgnoreProps.Contains(prop.Name))
            {
                continue;
            }

            var propType = prop.PropertyType;

            var newValue = prop.GetValue(newProp);
            var oldValue = prop.GetValue(oldProp);

            newValue = Convert.ChangeType(newValue, propType);
            oldValue = Convert.ChangeType(oldValue, propType);

            var a = Equals(newValue, oldValue); // return incorrect value

            if (!Equals(newValue, oldValue))
            {
                return true;
            }
        }

        return false;
    }

first object

second object





Aucun commentaire:

Enregistrer un commentaire