Find a private field with Reflection?

192,635

Solution 1

Use BindingFlags.NonPublic and BindingFlags.Instance flags

FieldInfo[] fields = myType.GetFields(
                         BindingFlags.NonPublic | 
                         BindingFlags.Instance);

Solution 2

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)
    ...

Solution 3

Get private variable's value using Reflection:

var _barVariable = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectForFooClass);

Set value for private variable using Reflection:

typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectForFoocClass, "newValue");

Where objectForFooClass is a non null instance for the class type Foo.

Solution 4

Nice Syntax With Extension Method

You can access any private field of an arbitrary type with code like this:

Foo foo = new Foo();
string c = foo.GetFieldValue<string>("_bar");

For that you need to define an extension method that will do the work for you:

public static class ReflectionExtensions {
    public static T GetFieldValue<T>(this object obj, string name) {
        // Set the flags so that private and public fields from instances will be found
        var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
        var field = obj.GetType().GetField(name, bindingFlags);
        return (T)field?.GetValue(obj);
    }
}

Solution 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.

Share:
192,635

Related videos on Youtube

David Basarab
Author by

David Basarab

David Basarab Software craftsman that is constantly scrubbing my code.

Updated on July 18, 2020

Comments

  • David Basarab
    David Basarab almost 4 years

    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?

  • Andy McCluggage
    Andy McCluggage over 15 years
    I could only get this to work by also supplying the "BindingFlags.Instance" binding flag.
  • lubos hasko
    lubos hasko about 15 years
    I have fixed your answer. It's too confusing otherwise. Abe Heidebrecht's answer was the most complete though.
  • Ramo
    Ramo almost 15 years
    Works great - FYI VB.NET version Me.GetType().GetFields(Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
  • ksun
    ksun over 9 years
    Using the instance binding flag is only if you want to get instance methods. If you wanted to get a private static method you can use (BindingFlags.NonPublic | BindingFlags.Static)
  • Brian Sweeney
    Brian Sweeney almost 9 years
    jammycakes could you please give an example of shared hosting environment? i'm thinking iis with multiple apps is what your're getting?
  • jammycakes
    jammycakes almost 9 years
    I'm talking about where IIS is locked down to partial trust at the machine.config level. You usually only find this on cheap-and-nasty shared web hosting plans these days (the likes of which I no longer use) -- if you have full control over your server then it won't really be relevant since full trust is the default.
  • Michael Freidgeim
    Michael Freidgeim almost 8 years
    Similar answer describes easy to use function GetInstanceField(typeof(YourClass), instance, "someString") as string How to get the value of private field in C#?
  • amnesia
    amnesia over 7 years
    Sorry for extreme necro-posting, but this threw me off. GetCustomAttributes(Type) will not return null if the attribute isn't found, it simply returns an empty array.
  • Hao Nguyen
    Hao Nguyen over 6 years
    To find the field name, it's easy to do in Visual Studio. Set breakpoint at the variable, view its fields (including the private, usually started with m_fieldname). Replace that m_fieldname in to the command above.
  • tayoung
    tayoung over 6 years
    Dude, this was PERFECT for accessing a protected variable without exposing it to NLua in my code! Awesome!
  • Leaky
    Leaky over 3 years
    BindingFlags.Instance trips me EVERY time I use reflection on non-public members. If you use GetFields() with Default=0 BindingFlags, you get instance members automatically. But when you set a binding flag explicitly, it deletes the default inclusion of instance members. It makes no sense. Flags enums should be additive.