Pages

Thursday 2 May 2013

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;
}
 
If you have any better approach to solve the above problem, please update me.

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.