Possible Duplicate:
What is “Best Practice” For Comparing Two Instances of a Reference Type?
I have this custom Class for my application. There are two instances (A and B) of this class, which I'm trying to compare. However, I'm having problems; I'm implementing the IEquatable<T>
interface to do this comparison, using an overridden Equals
methods.
The Equals
methods calls the ReferenceEquals
function, which is misbehaving.
Here are the test cases:
Case 1: A and B are different instances, and contain different data .. ReferenceEquals
says: They are different (which is correct !)
Case 2: A and B are different instances, but B was instantiated by using A's variable values (i.e. both A and B contain exactly same data!) .. ReferenceEquals
says: They are different (which is wrong !)
Case 3: A and B are same instances (i.e. A is passed in twice e.g. Equals (A, A)
) ReferenceEquals
says: They are same (which is correct !)
So how do I get the result of Case 2 to be correct as well ?
Class in which IEquatable<T>
is implemented:
namespace DBtestApp1
{
class QuantityBasedDiscount : IEquatable<QuantityBasedDiscount>
{
public string pType { get; set; }
public string pSubType { get; set; }
public DataTable quantityDiscountsDT { get; set; }
public QuantityBasedDiscount()
{
pType = "";
pSubType = "";
quantityDiscountsDT = new DataTable();
}
public QuantityBasedDiscount(string iProdType, string iProdSubType, DataTable iQuantitiesDT)
{
pType = iProdType;
pSubType = iProdSubType;
quantityDiscountsDT = iQuantitiesDT;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(Object obj)
{
var other = obj as QuantityBasedDiscount;
if (other == null) return false;
return Equals(other);
}
public bool Equals(QuantityBasedDiscount other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return false;
}
}
}
Code which calls the Equals
method (configured for Case 2 here):
private bool AnyUnsavedChanges()
{
QuantityBasedDiscount copyB = new QuantityBasedDiscount(copyA.pType, copyA.pSubType, copyA.quantityDiscountsDT);
if (copyA.Equals(copyB))
{
return false; //They are the same!
}
else
{
return true; //They are NOT the same!
}
}
So what's the problem in this code ?