Reputation: 4747
is there a straight forward way in .NET to compare two objects of same types.
Is there something like Compare(Object1, Object2) that can return a bool based on equality of the object properties values?
I have read about the IComparable and IComparer interfaces but I am looking at comparision of all the properties instead of just one or two.
Regards.
Upvotes: 1
Views: 56
Reputation: 2409
if I could also expand on that you can override the == and != operators of a particular class. I usually override all 3 (the equals, and the 2 operator) so that I can use unit tests to do somethign like
CustomClass customClass1 = new CustomClass("Robert");
CustomClass customClass2 = new CustomClass("Robert");
Assert.IsTrue(customClass1 == customClass2);
Assert.AreEqual(customClass1, customClass2);
comes in handy to have all options available if you ask me.
Upvotes: 0
Reputation: 1708
In general, what you describe is part of the contract of the Equals() method, depending on the particulars of the class in question.
Each class where it is relevant should implement Equals based on its own semantics.
Formally, per the Microsoft article
http://msdn.microsoft.com/en-us/library/vstudio/336aedhh(v=vs.100).aspx
the contract is:
x.Equals(x) returns true.
x.Equals(y) returns the same value as y.Equals(x).
(x.Equals(y) && y.Equals(z)) returns true if and only if x.Equals(z) returns true.
Successive invocations of x.Equals(y) return the same value as long as the objects referenced by x and y are not modified.
x.Equals(null) returns false.
Upvotes: 2