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?
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);
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)
{
}
....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With