0

I have a list of object like below

public class Person
{
   public string Name {get; set;}
   public int Age {get; set;}
}
public class SomeClass
{
public int DoSomething ()
{
    int result;
    List<Person> personList = new List<Person>();
    personList.Add(new Person { //with 1 object, just to keep simple
       Name = "Someone",
       Age = 18});
   Person eighteenYearsOld = _checkAge.FindEighteenYearsOld (personList);
   int index = personList.IndexOf (eighteenYearsOld);
   //do something
   return result;
}
}
[TestMethod]
public void DoSomething_Test()
{
    //Given:

    //When: I call SomeClass object
    Person eightnneYears = new Person {
       Name = "Someone",
       Age = 18};
   _mockCheckAge.Setup (x => x.FindEighteenYearsOld(It.IsAny<List<Person>>())).Returns(eightnneYears);
   _someClass = new SomeClass (_mockCheckAge.Object);
   int result = _someClass.DoSomething();
   //Then: 
}

As I have mocked the FindEighteenYearsOld method it returns a Person object with same states which is presents in the personList. But when personList.IndexOf() executes it returns index -1, which is suppose to be 0. What should I do.

Rahul Chakrabarty
  • 2,149
  • 7
  • 39
  • 70

1 Answers1

2

List.IndexOf uses Equals to find equal objects. If your class doesn't override it only references are compared. Since your two instances are not the same List.IndexOf returns -1.

So override Equals (and also always GetHashCode then):

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override bool Equals (Object obj)
    {
        Person otherPerson = obj as Person;
        return otherPerson != null 
            && otherPerson.Name == Name 
            && otherPerson.Age == Age;
    }

    // http://stackoverflow.com/a/263416/284240
    public override int GetHashCode()
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = 17;
            hash = hash * 23 + (Name?.GetHashCode() ?? 0); // or: hash = hash * 23 + (Name == null ? 0 : Name.GetHashCode());
            hash = hash * 23 + Age; ;
            return hash;
        }
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939