I was given this question at a job interview recently and couldn’t figure out how to do it elegantly. Ever since, it has been nagging away at me and I can’t work out if its a lack of knowledge about some ‘modern’ technique/technology I’m unaware of or if I’m just stupid. Any advice would be very welcome.
The Problem
Imagine a simple class hierarchy:
abstract class Person {
public string Name { get; set; }
}
class Child : Person { }
class Parent : Person {
public List<Person> Children { get; set; }
}
class Ancestor : Parent { }
The problem is how to traverse a hierarchy of such objects and to print out all the people encountered. So for the following scenario:
Ancestor myAncestor = new Ancestor {
Name = "GrandDad",
Children = new List<Person> {
new Child { Name = "Aunt" },
new Child { Name = "Uncle" },
new Parent {
Name = "Dad",
Children = new List<Person> {
new Child { Name = "Me" },
new Child { Name = "Sister" }
}
}
}
};
the output should be something like:
GrandDad
- Aunt
- Uncle
- *Dad
-Me
-Sister
All the processing needs to be done within a single method that accepts a single parameter of type Ancestor.
I implemented, almost without thinking, a simple recursive solution but of course because of the way the objects involved relate to each other things aren’t as simple as all that.
Try as I might I cannot think of a clean way of doing this and my post-interview Googlings have suggested I need to be doing something that is (to me, with only a working knowledge of LINQ and List<T>) something considerably more technically advanced than the sort of web-dev coding I’ve been doing for the last decade or so. Is this the case? Or should I be thinking of getting out of software development on the grounds that I’m rubbish at it?
Update
Thanks to you all for your responses/suggestions. I’ve accepted @Daniel Hilgarth’s answer primarily because it was the only one I could genuinely understand 😮
I agree with Marc’s comment saying that this type system is non-sense. Still, you can solve it with delegates. That’s a bit of cheating, because basically they are nothing more than methods, but here we go: