I would advise you to override the Equals method for your class to make the required comparison. This allows you to define equality of values ββinstead of referential equality. One caveat is that you should also override GetHashCode if you override Equals to ensure that two identical objects return the same hash code. Here is a very simple example:
public class Foo { public String Bar { get; set; } public String Baz { get; set; } public override Boolean Equals(Object other) { Foo otherFoo = other as Foo; return otherFoo != null && Bar.Equals(otherFoo.Bar) && Baz.Equals(otherFoo.Baz); } public override Int32 GetHashCode() { return Bar.GetHashCode() ^ Baz.GetHasCode(); } }
If you don't want to override Equals , and you really just want to compare instance properties by property, you can use reflection:
public static Boolean AreEqual<T>(T a, T b) { foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) if (!Object.Equals(propertyInfo.GetValue(a, null), propertyInfo.GetValue(b, null))) return false; return true; }
source share