I have a type like:
class Order
{
public List<IItem> AllItems { get; set; }
public string Name { get; set; }
public double TotalPurchases { get; set; }
public long Amount { get; set; }
public int Code { get; set; }
}
I've implemented the IEquatable<T>
interface to check if two objects of this type are same or not. The current Equals
method looks like:
public virtual bool Equals(Order other)
{
if ((object)other == null)
{
return false;
}
return (this.AllItems.Equals(other.AllItems)
&& this.Name.Equals(other.Name)
&& this.TotalPurchases.Equals(other.TotalPurchases)
&& this.Amount.Equals(other.Amount))
&& this.Code.Equals(other.Code));
}
But I wish to implement this method in such a way that it dynamically checks for equality of all the existing properties (or maybe certain properties of this type) without explicitly writing the code for comparison checks as above.
Hope I was able to express my question with clarity. :)
Thanks!
You could write a custom attribute that attaches to the properties on your type which you want to be included in the comparision. Then in the Equals method you could reflect over the type and extract all the properties which have the attribute, and run a comparison on them dynamically.
Psuedo code:
It'll certianly need to be a bit more elaborate than that, but that should hopefully set you on the right track :)