0

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?

Terkwood
  • 39
  • 2
  • 6
Milo
  • 35
  • 1
  • 7

1 Answers1

0

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[].

Shelby115
  • 2,816
  • 3
  • 36
  • 52