0

I wanna know how to count number of global variable exist in class which i called.

I used parameter with Several types of inherited classes, which are different number of variable.

And if possible i want to get name of variable..

public class MotherClass
{
    public int motherAge;
}

public class ChildClass : MotherClass {
    public int childAge;
    public string childName;
}

public void Main(MotherClass person) { 
    //count number of variable exist in "person"
    //get name of variables exist in "person"
}
Natejin
  • 55
  • 9
  • You must use reflection. see [How can I find all the public fields of an object in C#?](https://stackoverflow.com/questions/237275/how-can-i-find-all-the-public-fields-of-an-object-in-c) and many other examples. – Hamid Reza Mohammadi May 01 '20 at 13:01

1 Answers1

2

I assume by "global variable in class" you mean public field like public int motherAge;

using System.Reflection;
using System.Linq;
MotherClass person = new MotherClass();
var fields = person.GetType().GetFields().Where(i => i.IsPublic);
// Do something with fields.Count

foreach (FieldInfo item in fields)
{
  // Do something with item.Name;
}


Jarek Danielak
  • 394
  • 4
  • 18