2

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
Simon Price
  • 3,011
  • 3
  • 34
  • 98

1 Answers1

2

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();
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • 1
    Youre right, thank you. Its been one of those weeks where I have just not had the focus. As soon as I can mark it as an answer I will do (currently have to wait 8 more minutes) – Simon Price Feb 05 '21 at 13:57
  • By the way, you also had another error because you were only looking for static properties which you don't have, so you should have been using the default as above or `BindingFlags.Public | BindingFlags.Instance` – DavidG Feb 05 '21 at 14:10
  • Ive fixed that now too, but thank you for your kind help in this one :) – Simon Price Feb 05 '21 at 14:24