What am I missing in GetLowestLevelFoo? Why do I get the answer A instead of D?
public class Foo
{
public string Name { get; set; }
public Foo ChildFoo { get; set; }
}
[TestFixture]
public class Recursion
{
[Test]
public void Test()
{
Foo foo = new Foo
{
Name = "A",
ChildFoo = new Foo
{
Name = "B",
ChildFoo = new Foo
{
Name = "C",
ChildFoo = new Foo
{
Name = "D"
}
}
}
};
Assert.AreEqual("D", GetLowestLevelFoo(foo).Name);
}
public Foo GetLowestLevelFoo(Foo foo)
{
if (foo.ChildFoo != null)
{
GetLowestLevelFoo(foo.ChildFoo);
}
return foo;
}
}
You only want to return foo when you’r at the lowest level. You were returning it no matter what. If you’re not at the lowest level you should return the value returned from your recursive call.