Reputation: 3261
I have been tasked with updating a large number of records that all have the same data type and want to write this in such a way I don't have to find every class object and do them manually. Therefore, I thought the best way of doing this would be using reflection using PropertyInfo
.
Prior to asking this question I have looked at the following;
Getting ALL the properties of an object How to get the list of properties of a class? https://www.codegrepper.com/code-examples/csharp/c%23+get+all+class+properties https://learn.microsoft.com/en-us/dotnet/api/system.type.getproperties?view=net-5.0
looking at this, suggested I'm on the right approach, but for the life of me Im not getting the results.
The code is as follows
void Main()
{
var propeties = typeof(MaterialsStructure).GetProperties(BindingFlags.Public | BindingFlags.Static);
}
public class MaterialsStructure
{
public ExistingProposedDescriptionStructure boundariesField;
public ExistingProposedDescriptionStructure ceilingsField;
}
public class ExistingProposedDescriptionStructure
{
public string Existing { get; set; }
public string Proposed { get; set; }
public bool NotApplicable { get; set; }
public bool DontKnow { get; set; }
}
The problem is that when I inspect properties it has 0 items in the array, where I would have expected it to have two properties of type ExistingProposedDescriptionStructure
. I would be grateful if someone could show me where I have gone wrong here.
Upvotes: 2
Views: 253
Reputation: 119156
Your MaterialsStructure
class doesn't have properties, it has fields. See here for more detail on that. So either do this:
var fields = typeof(MaterialsStructure).GetFields();
Or change your class:
public class MaterialsStructure
{
public ExistingProposedDescriptionStructure boundariesField { get; set;}
public ExistingProposedDescriptionStructure ceilingsField { get; set;}
}
Now this will work:
var propeties = typeof(MaterialsStructure).GetProperties();
Upvotes: 2