Search code examples
c#reflectionpropertiesaccess-modifiers

Detect access modifier type on a property using Reflection


I have written some code to look at properties using reflection. I have retrieved a list of properties from the class using reflection.

However I need to find out if the property is public or protected. eg:

public string Name{get;set;}
protected  int Age{get;set;}

The PropertyInfo class does not seem to expose this information about the property. Is there another way to do this?


Solution

  • Since properties are just syntactic sugar over a pair of get/set methods, there's no such thing as "accessibility" of a property reflection-wise. Rather, you'll have to find out accessibility levels of get and set methods separately. To that end, retrieve appropriate MethodInfo objects with GetGetMethod and GetSetMethod methods, and from there are various IsPrivate, IsPublic and other methods and properties.