If you use ‘RemoveAll’ inside a generic class that you intend to be used to hold a collection of any type object, like this:
public class SomeClass<T>
{
internal List<T> InternalList;
public SomeClass() { InternalList = new List<T>(); }
public void RemoveAll(T theValue)
{
// this will work
InternalList.RemoveAll(x => x.Equals(theValue));
// the usual form of Lambda Predicate
// for RemoveAll will not compile
// error: Cannot apply operator '==' to operands of Type 'T' and 'T'
// InternalList.RemoveAll(x => x == theValue);
}
}
If you want to make the code as flexible as possible, you can use
EqualityComparer<T>.Defaultlike this:That code will work for any type of T (including nullable types and value types), it avoids boxing and it will also handle cases where T implements
IEquatable<T>or overridesobject.Equals. From the documentation: