views:

6486

answers:

5

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?

+3  A: 

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

mmattax
+5  A: 
typeof(MyType).GetField("fieldName", BindingFlags.NonPublic | BindingFlags.Instance)
Darren Kopp
I won't know the name of the field. I want to find it without the name and when the attribute is on it.
David Basarab
+19  A: 

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)
    ...
Abe Heidebrecht
+10  A: 

Use BindingFlags.NonPublic and BindingFlags.Instance flags

Reflection.FieldInfo fields[] = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
Bob King
I could only get this to work by also supplying the "BindingFlags.Instance" binding flag.
Andy McCluggage
Ain't it funny that everyone applauds this wrong answer and the correct answer from Abe Heidebrecht doesn't get any points.
Phil Bachmann
I would gladly delete my answer, but it's marked 'accepted'.
Bob King
I have fixed your answer. It's too confusing otherwise. Abe Heidebrecht's answer was the most complete though.
lubos hasko
Works great - FYI VB.NET versionMe.GetType().GetFields(Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
gg
+5  A: 

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.

jammycakes