tags:

views:

1324

answers:

5

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?

+2  A: 

You need to override Equals and GetHashCode in your class (MyType).

Can Berk Güder
A: 

If you implement the equals of you custom type, the contains function of List will work

PoweRoy
No, List<T> will never use the == operator; only Equals
Marc Gravell
Don't think it deserved a downvote, though. The Equals is true; fixed that (+1)
Marc Gravell
+2  A: 

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

    }

    ....
}
Peter Lillevold
+2  A: 

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);
Marc Gravell
@Marc Gravell: so if I want to test the 'equality' of 2 custom classes that only contain properties and fields, I need to implement IEquatable in my class? I must have been really tired when I made the assumption that 2 classes would be considered 'equal' just because the fields contained the same values in each class. :/ ...thanks for the tip ;)
dboarman
@Marc Gravell: well, technically, it wouldn't matter what they contain. What is important is that I 'properly' implement IEquatable<MyClass> and select the field that should dictate whether another MyClass is considered equal.
dboarman
@dboarman - exactly. And re your first point, IIRC structs *do* behave like that, so you weren't a million miles off.
Marc Gravell
A: 

Depending on what specific needs you have in your override you might use Linq expression for doing that:

list.Any(x => x.Name.Equals("asdas", .....)) // whatever comparison you need

You can then wrap it in an extension method for convenience.

Rashack