Detect access modifier type on a property using Reflection

Michael Edwards picture Michael Edwards · Mar 11, 2010 · Viewed 7.9k times · Source

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?

Answer

Anton Gogolev picture Anton Gogolev · Mar 11, 2010

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.