Given this class
class Foo
{
// Want to find _bar with reflection
[SomeAttribute]
private string _bar;
public string BigBar
{
get { return this._bar; }
}
}
I want to find the private item _bar that I will mark with a attribute. Is that possible?
I have done this with properties where I have looked for an attribute, but never a private member field.
What are the binding flags that I need to set to get the private fields?
Yes, however you will need to set your Binding flags to search for private fields (if your looking for the member outside of the class instance).
The binding flag you will need is: System.Reflection.BindingFlags.NonPublic
I use this method personally
Nice Syntax With Extension Method
You can access any private field of an arbitrary type with code like this:
For that you need to define an extension method that will do the work for you:
Get private variable's value using Reflection:
Set value for private variable using Reflection:
Where objectForFooClass is a non null instance for the class type Foo.
Here is some extension methods for simple get and set private fields and properties (properties with setter):
usage example:
Code:
One thing that you need to be aware of when reflecting on private members is that if your application is running in medium trust (as, for instance, when you are running on a shared hosting environment), it won't find them -- the BindingFlags.NonPublic option will simply be ignored.