I’m trying to perform a good comparison when I use List.Contains(T item).
The problem is that I’m using BaseItem as a list item. And I need to verify if one object inside of the list has the same properties values that the object which I plan to add.
For example:
public abstract class BaseItem
{
// some properties
public override bool Equals(object obj)
{
return obj != null && this.GetType() == obj.GetType();
}
}
public class ItemA : BaseItem
{
public int PropertyA { get; set; }
public override bool Equals(object obj)
{
if (base.Equals(obj) == false)
return false;
return (this.PropertyA == (obj as ItemA).PropertyA;
}
}
public class ItemB : BaseItem
{
public int PropertyB { get; set; }
public override bool Equals(object obj)
{
if (base.Equals(obj) == false)
return false;
return this.PropertyB == (obj as ItemB).PropertyB;
}
}
public class Program
{
static void Main(string[] args)
{
List<BaseItem> items = new List<BaseItem>()
{
new ItemB() { PropertyB = 3 },
new ItemA() { PropertyA = 2 },
new ItemB() { PropertyB = 2 }
};
BaseItem newItem = new ItemA() { PropertyA = 2 };
items.Contains(newItem); // should return 'True', because the first element is equals than 'newItem'
}
}
I’m not sure if it’s correct to override Equals method or should I have to implement IEquality interface.
The standard way to test for collection membership (list membership, hashset membership, …) is to use the .Contains method, which in turn uses
IEquatable<T>.Equals. The default implementation ofIEquatable<T>.Equals(if you do not provide your own implementation) usesObject.Equals(Object)).You can certainly implement
IEquatable<T>. This will improve performance of the Contains check slightly. See msdn.microsoft.com/en-us/library/ms131190.aspx.If you implement
IEquatable<T>you should still overrideObject.EqualsandObject.GetHashCodeto provide consistent behaviorhttp://msdn.microsoft.com/en-us/library/ms131190.aspx
See this question for a related discussion
Simplify Overriding Equals(), GetHashCode() in C# for Better Maintainability