mercredi 20 mars 2019

Reflection: how does PropertyInfo.GetValue deal with null values?

I have this code to compare two objects:

public static List<Variance> DetailedCompare<T>(this T val1, T val2)
    {
        List<Variance> variances = new List<Variance>();
        PropertyInfo[] fi = val1.GetType().GetProperties();

        foreach (PropertyInfo f in fi)
        {
            Variance v = new Variance();
            v.Property = f.Name;
            v.valueA = f.GetValue(val1);
            v.valueB = f.GetValue(val2);

            if (!Equals(v.valueA, v.valueB))
                variances.Add(v);                            
        }
        return variances;
    }

If a property on both objects has a value and isn't equal then it works fine, that property is returned in my variances collection, but if one of the properties is null then it isn't returned.

How can I change it so a null value gets compared and is detected as being !Equal to the other property that has a value.

Thanks





Aucun commentaire:

Enregistrer un commentaire