Contains
will use the default equality comparer for the type when trying to find a match, which is a reference comparison for reference types like classes. Since we know that there is no reference to the object you just created in the list, this will not work.
One simple way around this is to use the System.Linq
method Any()
, which returns true if any items in an IEnumerable
meet the specified conditions.
For example:
Assert.IsTrue(results.Any(result =>
result.decimalField1 == expectedItem.decimalField1 &&
result.intField2 == expectedItem.intField2));
A slightly more laborious but re-usable way to do this is to write a SomeNestedClass
comparer that can be passed to the Contains
method (I'm using SomeNestedClass
even though result
was declared as a MyClass
in the example because that's the only class that has fields we can use for comparison):
public class SomeNestedClassComparer : IEqualityComparer<MyClass.SomeNestedClass>
{
public bool Equals(MyClass.SomeNestedClass x, MyClass.SomeNestedClass y)
{
if (x == null || y == null) return ReferenceEquals(x, y);
return x.decimalField1 == y.decimalField1 && x.intField2 == y.intField2;
}
public int GetHashCode(MyClass.SomeNestedClass obj)
{
return obj.decimalField1.GetHashCode() * 17 +
obj.intField2.GetHashCode();
}
}
And now we tell Contains
to use this class when trying to find a match for our expectedItem
:
Assert.IsTrue(results.Contains(expectedItem, new SomeNestedClassComparer()));