Can I read properties before creating an object? In the constructor?

Is it possible to count the number of properties in a class before creating an object? Can I do this in the constructor?

class MyClass { public string A { get; set; } public string B { get; set; } public string C { get; set; } public MyClass() { int count = //somehow count properties? => 3 } } 

thanks

+4
source share
4 answers

Yes, you can:

 class MyClass { public string A { get; set; } public string B { get; set; } public string C { get; set; } public MyClass() { int count = this.GetType().GetProperties().Count(); // or count = typeof(MyClass).GetProperties().Count(); } } 
+11
source

It is possible to use reflection, as shown by BigYellowCactus. But there is no need to do this in the constructor every time, because the number of properties never changes.

I would suggest doing this in a static constructor (called only once for each type):

 class MyClass { public string A{ get; set; } public string B{ get; set; } public string C{ get; set; } private static readonly int _propertyCount; static MyClass() { _propertyCount = typeof(MyClass).GetProperties().Count(); } } 
+5
source
 public MyClass() { int count = GetType().GetProperties().Count(); } 
+3
source

Use this to count the number of properties contained in your class.

 Type type = typeof(YourClassName); int NumberOfRecords = type.GetProperties().Length; 
0
source

All Articles