I have a class like this
public class TestData
{
public string Name {get;set;}
public string type {get;set;}
public List<string> Members = new List<string>();
public void AddMembers(string[] members)
{
Members.AddRange(members);
}
}
I want to know if it is possible to directly compare to instances of this class to eachother and find out they are exactly the same? what is the mechanism? I am looking gor something like if(testData1 == testData2) //Do Something
And if not, how to do so?
Implement the
IEquatable<T> interface
. This defines a generalized method that a value type or class implements to create a type-specific method for determining equality of instances. More information here:http://msdn.microsoft.com/en-us/library/ms131187.aspx
First of all equality is difficult to define and only you can define as to what equality means for you
Here is a discussion and an answer here
What is "Best Practice" For Comparing Two Instances of a Reference Type?
You will need to define the rules that make object A equal to object B and then override the Equals operator for this type.
http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
I see many good answers here but just in case you want the comparison to work like
instead of using Equals function you can override == and != operators:
There are three ways objects of some reference type
T
can be compared to each other:object.Equals
methodIEquatable<T>.Equals
(only for types that implementIEquatable<T>
)==
Furthermore, there are two possibilities for each of these cases:
T
(or some other base ofT
)object
The rules you absolutely need to know are:
Equals
andoperator==
is to test for reference equalityEquals
will work correctly no matter what the static type of the objects being compared isIEquatable<T>.Equals
should always behave the same asobject.Equals
, but if the static type of the objects isT
it will offer slightly better performanceSo what does all of this mean in practice?
As a rule of thumb you should use
Equals
to check for equality (overridingobject.Equals
as necessary) and implementIEquatable<T>
as well to provide slightly better performance. In this caseobject.Equals
should be implemented in terms ofIEquatable<T>.Equals
.For some specific types (such as
System.String
) it's also acceptable to useoperator==
, although you have to be careful not to make "polymorphic comparisons". TheEquals
methods, on the other hand, will work correctly even if you do make such comparisons.You can see an example of polymorphic comparison and why it can be a problem here.
Finally, never forget that if you override
object.Equals
you must also overrideobject.GetHashCode
accordingly.You can override the equals method and inside it manually compare the objects
Also take a look at Guidelines for Overloading Equals() and Operator ==