How to get the value of private field using reflection?

Viewed 64547

I ran into a problem that I need to access to private field of a class. For example:

class MyClass 
{
    private string someString;

    public MyClass( string someStringValue )
    {
        someString = someStringValue;
    }
}

How can I get the value of someString outside MyClass ?

Update:

Sorry, I cannot use property here since the the actual production code is protected. I'm a QA/Dev, I need a way to get those private for writing User Acceptance Test. So I cannot change production code. Can you help?

7 Answers

Here is a working generics version as clean as I can get it.

private static object GetInstanceField<T>(T instance, string fieldName)
{                
    BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
    FieldInfo field = typeof(T).GetField(fieldName, bindFlags);
    return field.GetValue(instance);
}

usage

var str = (string)GetInstanceField(instance, "someString");
Related