Search code examples
c#classpropertiessubclassing

How do I automatically display all properties of a class, which is a property in another class?


I want to print all values of my class, similar to this question. The difference is that my class is a property in another class. I tried following simple code:

public class ClassA
{
    public double PropA = 5;
    private PropertyInfo[] _PropertyInfos = null;
    public void Print()
    {
        if (_PropertyInfos == null)
            _PropertyInfos = this.GetType().GetProperties();

        foreach (var info in _PropertyInfos)
        {
            Console.WriteLine(info.Name + ": " + info.GetValue(this).ToString());
        }
    }
}

public class ClassB
{
    public ClassA PropB = new ClassA();
}

class Program
{
    static void Main(string[] args)
    {
        ClassB classB = new ClassB();

        classB.PropB.Print();
    }
}

For some reason _PropertyInfos is always void, so he skips the entire loop. What am I doing wrong?


Solution

  • ClassA has no properties, only fields.

    public double PropA = 5;          // Field
    public double PropA { get; set; } // Property
    

    _PropertyInfos isn't null, it's empty.

    Either convert your fields to properties or start using this.GetType().GetFields() swapping PropertyInfo[] for FieldInfo[].