As you already figured out, one way to access a non-public setter is as follows:
PropertyInfo property = typeof(Type).GetProperty("Property");
property.DeclaringType.GetProperty("Property");
property.GetSetMethod(true).Invoke(obj, new object[] { value });
There is another way, though:
PropertyInfo property = typeof(Type).GetProperty("Property");
// if Property is defined by a base class of Type, SetValue throws
property = property.DeclaringType.GetProperty("Property");
property.SetValue(obj, value, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null); // If the setter might be public, add the BindingFlags.Public flag.
Coming here from a search engine?
This question is specifically about accessing a non-public setter in a public property.
- If both the property and setter are public, only the first example will work for you. To get the second example to work, you will need to add the
BindingFlags.Public
flag. - If the property is declared in a parent type and not visible to the type on which you’re calling
GetProperty
, you won’t be able to access it. You’ll need to callGetProperty
on a type to which the property is visible. (This doesn’t affect private setters as long as the property itself is visible.) - If there are multiple declarations for the same property in the inheritance chain (via the
new
keyword), these examples will target the property that is immediately visible to the type on whichGetProperty
is called. For example, if class A declares Property usingpublic int Property
, and class B re-declares Property viapublic new int Property
,typeof(B).GetProperty("Property")
will return the property declared in B, whiletypeof(A).GetProperty("Property")
will return the property declared in A.