compare the properties of two objects class

Use reflection to compare the properties of two objects class

internal static class ObjectHelper<T>
{
    public static void Compare(T x, T y)
    {
        Type type = typeof(T);
        PropertyInfo[] properties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
        FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
        int compareValue = 0;

        foreach (PropertyInfo property in properties)
        {
            IComparable valx = property.GetValue(x, null) as IComparable; // new value
            if (valx == null) continue;
            object valy = property.GetValue(y, null); // old value
            compareValue = valx.CompareTo(valy);
            if (compareValue != 0)
                 return compareValue;
        }
       return compareValue;
     }
}


How to use this
class1 n1 = new class1();
n1.Name = "bhaumik";

class1 n2 = new class1 ();
n2.Name = "bhaumik";

int result1 = ObjectHelper<class1>.Compare(n1, n2);
// result1 == 0 because n1 and n2 have equal properties

n1.Name = "patel";
// change the first name, so n1 should no longer equal n2

int result2 = ObjectHelper<class1>.Compare(n1, n2);
// result2 != 0 because n1 and n2 do not have equal properties


compare the properties of two objects class compare the properties of two objects class Reviewed by Bhaumik Patel on 2:57 AM Rating: 5