What does Collection.Contains() use to check for existing objects?

topwik picture topwik · Sep 3, 2010 · Viewed 49.2k times · Source

I have a strongly typed list of custom objects, MyObject, which has a property Id, along with some other properties.

Let's say that the Id of a MyObject defines it as unique and I want to check if my collection doesn't already have a MyObject object that has an Id of 1 before I add my new MyObject to the collection.

I want to use if(!List<MyObject>.Contains(myObj)), but how do I enforce the fact that only one or two properties of MyObject define it as unique?

I can use IComparable? Or do I only have to override an Equals method? If so, I'd need to inherit something first, is that right?

Answer

Jon Hanna picture Jon Hanna · Sep 3, 2010

List<T>.Contains uses EqualityComparer<T>.Default, which in turn uses IEquatable<T> if the type implements it, or object.Equals otherwise.

You could just implement IEquatable<T> but it's a good idea to override object.Equals if you do so, and a very good idea to override GetHashCode() if you do that:

public class SomeIDdClass : IEquatable<SomeIDdClass>
{
    private readonly int _id;
    public SomeIDdClass(int id)
    {
        _id = id;
    }
    public int Id
    {
        get { return _id; }
    }
    public bool Equals(SomeIDdClass other)
    {
        return null != other && _id == other._id;
    }
    public override bool Equals(object obj)
    {
        return Equals(obj as SomeIDdClass);
    }
    public override int GetHashCode()
    {
        return _id;
    }
}

Note that the hash code relates to the criteria for equality. This is vital.

This also makes it applicable for any other case where equality, as defined by having the same ID, is useful. If you have a one-of requirement to check if a list has such an object, then I'd probably suggest just doing:

return someList.Any(item => item.Id == cmpItem.Id);