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

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);

Leave a Comment