GetMethod only searches the public method, but with GetProperty, we get the public auto property with a private set, and we can set the value to this property. Can somebody explain why?
-
By default reflection always searches only public things (you can also include privates with a parameter). Since the property is public, it finds it, even though the setter (or even the getter for the matter) happens to be private. – Alejandro Jul 19 '21 at 16:19
-
3You can definitely invoke private methods using reflection. See https://stackoverflow.com/a/135482 – inquisitive Jul 19 '21 at 16:22
-
Restrictions imposed by the C# language ≠ restrictions imposed by the CLR, IL or Reflection. C# is often more restrictive (and safer). – Olivier Jacot-Descombes Jul 19 '21 at 16:50
-
Technically speaking, the property itself has an accessibility, apart from the `get` and `set`, just that C# always enforces the wider of the two. So `GetProperty` searches that accessibility – Charlieface Jul 19 '21 at 16:51
1 Answers
A method has only the one accessibility level, whatever you've defined for that method. The GetMethod
overloads that don't take a binding flags search only the public methods. It's simply how GetMethod
was implemented.
Properties have an accessibility level for each of the get
and the set
. GetProperty
overloads that don't take binding flags also search only the public properties; if either get
or set
are public, you'll get the property you're searching for (if it exists of course).
The private setter of the property allows access to set the property through reflection as long as the calling code has permission to get to the private property's set method (see Security Considerations for Reflection). Remember, an auto property is backed by a private field and has two methods (internally generated getter and setter).

- 20,354
- 4
- 60
- 103
-
OP did say "property with private set", but to help with completeness for future readers: some read-only property implementations use [expression-bodied members](https://stackoverflow.com/q/31764532/3791245). Per the end of this [answer](https://stackoverflow.com/a/3706485/3791245), such implementations can't be set via the usual reflection methods (e.g. `PropertyInfo.SetValue`). – Sean Skelly Jul 19 '21 at 16:49