It's pretty simple. You need to get the type of your target object with typeof
or GetType()
if you have an instance like in this case. Then you can use GetField
to get the desired field. But there is a catch. GetField
by default only search for fields that are public and non-static. TO chage that you need to give it some BindingFlags
. An Example:
public static string ReadPrivateField(object obj, string fieldName)
{
var type = obj.GetType();
// NonPublic = obly search for private fields.
// Instance = only search for non-static fields.
var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
return field.GetValue(obj) as string;
}