Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if property setter is public

Given a PropertyInfo object, how can I check that the setter of the property is public?

like image 799
Ronnie Overby Avatar asked Sep 21 '10 16:09

Ronnie Overby


2 Answers

Check what you get back from GetSetMethod:

MethodInfo setMethod = propInfo.GetSetMethod();  if (setMethod == null) {     // The setter doesn't exist or isn't public. } 

Or, to put a different spin on Richard's answer:

if (propInfo.CanWrite && propInfo.GetSetMethod(/*nonPublic*/ true).IsPublic) {     // The setter exists and is public. } 

Note that if all you want to do is set a property as long as it has a setter, you don't actually have to care whether the setter is public. You can just use it, public or private:

// This will give you the setter, whatever its accessibility, // assuming it exists. MethodInfo setter = propInfo.GetSetMethod(/*nonPublic*/ true);  if (setter != null) {     // Just be aware that you're kind of being sneaky here.     setter.Invoke(target, new object[] { value }); } 
like image 114
Dan Tao Avatar answered Sep 20 '22 21:09

Dan Tao


.NET properties are really a wrapping shell around a get and set method.

You can use the GetSetMethod method on the PropertyInfo, returning the MethodInfo referring to the setter. You can do the same thing with GetGetMethod.

These methods will return null if the getter/setter is non-public.

The correct code here is:

bool IsPublic = propertyInfo.GetSetMethod() != null; 
like image 41
David Pfeffer Avatar answered Sep 21 '22 21:09

David Pfeffer