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.