Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override .NET Generic List<MyType>.Contains(MyTypeInstance)?

Tags:

c#

.net

list

Is it possible, and if so how do I override the Contains method of an otherwise normal List<T>, where T is my own, custom type?

like image 949
Jörg Battermann Avatar asked Apr 08 '09 08:04

Jörg Battermann


2 Answers

List<T> uses EqualityComparer<T>.Default to do comparisons; this checks first to see if your object implements IEquatable<T>; otherwise is uses object.Equals.

So; the easiest thing to do is to override Equals (always update GetHashCode to match the logic in Equals). Alternatively, use LINQ instead:

bool hasValue = list.Any(x => x.Foo == someValue);
like image 76
Marc Gravell Avatar answered Oct 14 '22 08:10

Marc Gravell


To make your own Contains implementation you could create a class that implements the IList interface. That way your class will look like a IList. You could have a real List internally to do the standard stuff.

class MyTypeList : IList<MyType>
{
    private List<MyType> internalList = new ...;

    public bool Contains(MyType instance)
    {

    }

    ....
}
like image 35
Peter Lillevold Avatar answered Oct 14 '22 08:10

Peter Lillevold