Find a private field with Reflection?


Given this class

class Foo
    // Want to find _bar with reflection
    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?

1/31/2015 3:47:07 PM

Accepted Answer

Use BindingFlags.NonPublic and BindingFlags.Instance flags

FieldInfo[] fields = myType.GetFields(
                         BindingFlags.NonPublic | 
1/11/2012 6:58:34 PM

You can do it just like with a property:

FieldInfo fi = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance);
if (fi.GetCustomAttributes(typeof(SomeAttribute)) != null)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow