Bohn Bohn - 1 month ago 28
C# Question

Finding the number of object behind a property

In some code like this:

public class MatryoshkaDoll
{
private readonly MatryoshkaDoll containedDoll;

public MatryoshkaDoll() { }

public MatryoshkaDoll(MatryoshkaDoll containedDoll)
{
this.containedDoll = containedDoll;
}

public int NumberOfSmallerDolls
{
get
{
//???
}
}

public static void Main(string[] args)
{
Console.WriteLine(new MatryoshkaDoll(new MatryoshkaDoll()).NumberOfSmallerDolls);
}
}


I though C# might have a
.Parent
property but I was wrong. So let's say we run the code

Console.WriteLine(new MatryoshkaDoll(new MatryoshkaDoll()).NumberOfSmallerDolls);


It should return 1 and I thought I can go back to Parent until it is null and count it to know how many dolls are inside. But I was wrong, no Parent. So how do we implement that NumberOfSmallerDolls property?

Answer

You can use recursion:

public int NumberOfSmallerDolls
{
    get
    {
        if (containedDoll == null) return 0;
        return 1 + containedDoll.NumberOfSmallerDolls;
    }
}

Because recursion is sometimes difficult to understand, here's another way of thinking about which might be clearer:

public int NumberOfSmallerDolls
{
    get
    {
        int count = 0;
        if (containedDoll != null) {
            count += 1;                                     // count containedDoll
            count += containedDoll.NumberOfSmallerDolls;    // count the dolls inside it
        }
        return count;
    }
}