Q:

C# Counting properties of Class with child/nested objects

I have the following construction of classes, here simplified as child classes of a 'mother' class called DataClass, which also contains one simple method:
public class DataClass
{
    public int num { get; set; }
    public string code { get; set; }
    public PartClass part { get; set; }
    public MemberClass member { get; set; }

    public int Count()
    {
        Type t = typeof(DataClass);
        return typeof(DataClass).GetProperties().Length;
    }
}

public class PartClass
{
    public int seriesNum { get; set; }
    public string seriesCode { get; set; }
}

public class MemberClass
{
    public int versionNum { get; set; }
    public SideClass side { get; set; }
}

public class SideClass
{
    public string firstDetail { get; set; }
    public string secondDetail { get; set; }
    public bool include { get; set; }
}

The issue is, I want to refactor the method so that it can give me an accurate counting of all properties found, including the ones in nested or child classes. In the above example, it only counts properties of DataClass, while I wanted it to return 2 for DataClass + 2 for PartClass + 1 for MemberClass + 3 for SideClass, sums up to 8 properties you may set through DataClass.
Can someone help me with this?

A:

You can introduce interface with Count() method
public interface ICountable
{
    int Count();
}

And use this interface to mark all types, which properties are participating in Count() calculation.
You can see the generic abstract class to implement this interface below. Generic T parameter is type whose properties need to be calculated. You implement a calculation logic only once and inherit this class where needed. You also go through all of properties, implementing ICountable, to calculate them as well (some kind of recursion)
public abstract class Countable<T> : ICountable
{
    public int Count()
    {
        Type t = typeof(T);
        var properties = t.GetProperties();
        var countable = properties.Select(p => p.PropertyType).Where(p => typeof(ICountable).IsAssignableFrom(p));
        var sum = countable.Sum(c => c.GetProperties().Length);
        return properties.Length + sum;
    }
}

and inherit it in your classes
public class DataClass : Countable<DataClass>
{
...
}

public class PartClass : Countable<PartClass>
{
...
}

public class MemberClass : Countable<MemberClass>
{
...
}

public class SideClass : Countable<SideClass>
{
...
}

And this is for the test
var dataClass = new DataClass();
var count = dataClass.Count();

It returns 8 as expected

