Coder Perfect

Reflection can help you find a secluded field.


Given this class

class Foo
    // Want to find _bar with reflection
    private string _bar;

    public string BigBar
        get { return this._bar; }

I’m looking for the private object _bar, which I’m going to attribute. Is that something you can do?

I’ve done this before with properties when looking for an attribute, but never with a private member field.

What binding flags do I need to set in order to access the private fields?

Asked by David Basarab

Solution #1

BindingFlags should be used. NonPublic and BindingFlags are two types of flags. Flags for instances

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

Answered by Bob King

Solution #2

You can do it the same way you would with a decent

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

Answered by Abe Heidebrecht

Solution #3

Reflection is used to get the value of a private variable:

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

Reflection is used to set the value of a private variable:

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

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

Answered by Suriya

Solution #4

When reflecting on private members, one thing to keep in mind is that if your application is running in medium trust (like, for example, on a shared hosting environment), it won’t find them — the BindingFlags. The NonPublic option will be ignored entirely.

Answered by jammycakes

Solution #5

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

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

To do so, create an extension method that will handle the task 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);

Answered by Bruno Zell

Post is based on