How to count number of data members in a C# class at runtime?
How to count number of data members in a C# class at runtime?
While development of one of my C# .NET project, I felt the need to count the number of data members at runtime and do something with them. I used typeof(ClassName).GetFields().Length to solve the problem like following.
using System;
public class Test
{
public static void Main()
{
var count = typeof(ABC).GetFields().Length;
Console.WriteLine(count);
}
}
static class ABC
{
public static int A;
public static int B;
public static int C;
}
public class Test
{
public static void Main()
{
var count = typeof(ABC).GetFields().Length;
Console.WriteLine(count);
}
}
static class ABC
{
public static int A;
public static int B;
public static int C;
}
If you have any better approach to solve the above problem, please update me.