0

I'm trying to extract all public properties (whether they use get/set or not) of a class using reflection. However, I find that I can only retrieve the properties that use get/set following Get property value from string using reflection.

class ClassA
    {
        public string layout { get; set; }
        public int capacity { get; set; }
        public Link[] links;
        public ClassA(int n)
        {
            capacity = n;
            links = new Link[n];
            for (int i = 0; i < n; i++)
            {
                links[i] = new Link();
            }
        }
    }

take the above class as an example. I can only get layout and capacity through reflection. Is there any way I can get "links"?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 3
    "I'm trying to extract all public properties...Is there any way I can get "links"?" `links` is simply not a property. It is a field and there is an extra reflection method to [get the fields](https://learn.microsoft.com/en-us/dotnet/api/system.type.getfields?view=net-5.0). – Mong Zhu Sep 10 '21 at 06:45
  • 1
    thx! @MongZhu So if I want to get both props and fields, the only way I can do this is to scan twice, one for props and one for fields, right? – void of null Sep 10 '21 at 06:51
  • 2
    No, you don't have to scan 2 times. You ca use `GetMembers` method instead and filter the collection with MemberTypes equals to `Property` or `Field` – Eldar Sep 10 '21 at 06:58
  • 1
    Side note: public fields are excitingly rare in real code... so depending on your goals getting just properties may be enough. – Alexei Levenkov Sep 10 '21 at 07:07

0 Answers0