2

I have following class in c#. How can I count number of data members at runtime?

public static class ABC
{
  public static string A;
  public static string B;
  public static string C;
}

Bascially, I have to iterate each datamember and pass it to some function one by one which will assign it some value. Thats why I need this.

If its not possible, is there any other way to do same

2 Answers2

5

Here is one way to do it:

var count = typeof(ABC).GetFields().Length;

Each element of the array returned by GetFields corresponds to a data member. In addition to getting the count, you can further examine each field - get its name, check its type and so on. You can also use FieldInfo objects to get and/or set fields of your target class.

Demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Something along these lines shall work. Generally you would use reflection for this kind of things.

int count = typeof(ABC)
    .GetFields()
    .Count();

@dasblinkenlight solution is better, because .Length performs in O(1), whereas my .Count() is O(N).

Side note, I am sure you know this, public fields are evil, consider using properties instead.

oleksii
  • 35,458
  • 16
  • 93
  • 163