You can do this with the help of reflection, but it is not fast, but you can create a method for comparison once and cache it. If you have a lot of such comparisons in the code, then this is not the worst option:
static class ComparerEx { public static bool IsEqual<T>(this T obj1, T obj2) => ComparerImpl<T>.IsEqual(obj1, obj2); private class ComparerImpl<T> { static ComparerImpl() { var parameters = new[] { Expression.Parameter(typeof(T), "x"), Expression.Parameter(typeof(T), "y") }; Expression body = Expression.Constant(true, typeof(bool)); var memberTypes = new[] { MemberTypes.Field, MemberTypes.Property }; foreach (var member in typeof(T).GetMembers().Where(m => memberTypes.Contains(m.MemberType))) body = Expression.AndAlso(body, Expression.Equal( Expression.MakeMemberAccess(parameters[0], member), Expression.MakeMemberAccess(parameters[1], member))); var lambda = Expression.Lambda<Func<T, T, bool>>(body, parameters); //Console.WriteLine(lambda); IsEqual = lambda.Compile(); } public static readonly Func<T, T, bool> IsEqual; } }
After that you can write something like:
class A { public int Prop1 { get; set; } public string Prop2 { get; set; } public int Field1; }
and
var a1 = new A { Prop1 = 1, Prop2 = "1", Field1 = 11 }; var a2 = new A { Prop1 = 1, Prop2 = "1", Field1 = 11 }; var r = a1.IsEqual(a2); // вернет true Console.WriteLine(r);