Find a private field with Reflection?

Given this class

class Foo
{
    // Want to find _bar with reflection
    [SomeAttribute]
    private string _bar;

    public string BigBar
    {
        get { return this._bar; }
    }
}

I intend to locate the exclusive thing _ bar that I will certainly note with a feature. Is that feasible?

I have actually done this with buildings where I have actually sought a feature, yet never ever an exclusive participant area.

What are the binding flags that I require to set to get the exclusive areas?

263
2022-07-01 20:13:18
Source Share
Answers: 5

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.

24
2022-07-02 23:25:19
Source

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

5
2022-07-02 23:10:19
Source

You can do it similar to with a property:

FieldInfo fi = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance);
if (fi.GetCustomAttributes(typeof(SomeAttribute)) != null)
    ...
176
2022-07-01 20:29:39
Source
typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)
18
2022-07-01 20:28:38
Source

Use BindingFlags.NonPublic and also BindingFlags.Instance flags

FieldInfo[] fields = myType.GetFields(
                         BindingFlags.NonPublic | 
                         BindingFlags.Instance);
329
2022-07-01 20:27:51
Source