I need to write a generic method in the base class that would accept 2 objects as parameters and compares them for equality.
Ex:
public abstract class BaseData
{
public bool AreEqual(object O1, object O2)
{
//Need to implement this
}
}
public class DataTypeOne : BaseData
{
public string Name;
public string Address;
}
public class DataTypeTwo : BaseData
{
public int CustId;
public string CustName;
}
The AreEqual()
method would accept 2 instances of DataTypeOne
or 2 instances of DataTypeTwo
.
My guess is I need to use Reflection? I can use LINQ if it can be more readable/concise.
EDIT: The reason I would like to implement this method in the base class is because of project restrictions. There are a large number of devs working on the derived classes. By implementing this in the base class, I am trying to have 1 less thing for them to worry about.
(Assuming that what you want is to compare all the fields of the two objects for equality.)
Usually, you wouldn't bother using reflection for this, you'd just compare each field yourself. The IEquatable<T>
interface exists for this purpose, and you also might want to override Object.Equals()
on the types in question. For example:
public class DataTypeTwo : BaseData, IEquatable<DataTypeTwo>
{
public int CustId;
public string CustName;
public override int GetHashCode()
{
return CustId ^ CustName.GetHashCode(); // or whatever
}
public override bool Equals(object other)
{
return this.Equals(other as DataTypeTwo);
}
public bool Equals(DataTypeTwo other)
{
return (other != null &&
other.CustId == this.CustId &&
other.CustName == this.CustName);
}
}
Also, consider whether or not your type makes sense as a struct
instead. Value types automatically compare equality by doing a field-by-field comparison.
Note that by overriding Equals
, you basically achieve what (it seems to me) you're trying to achieve with your "master equals method" scheme. That is, people using DataTypeTwo
will be able to naturally test for equality without having to know anything special about your API -- they'll just use Equals
like they would with other things.
EDIT: Thanks to Jared for reminding me about GetHashCode
. You'll also want to override it to maintain normal-looking behavior in hashtables by making sure that any two objects which are "equal" also return the same hash code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With