0

How do I get any object and its private field read and then returned

public class Person
{
    private string _password;


    }

    public string Name { get; set }

    public Gender man { get; set }

    public int Age { get; set }
}

Here is the class from which you have to get the data

jayy91
  • 11
  • 3
  • 1
    You need to put stuff in `ReadPrivateField` i'm guessing :) – TheGeneral Mar 25 '19 at 10:03
  • 1
    If you are asking whether you can get the backing field to a property, you can only do it with an auto implemented property, otherwise it could be anything, Even then this could be hit or miss im thinking – TheGeneral Mar 25 '19 at 10:05
  • Okay, and how do I do that? Look update. – jayy91 Mar 25 '19 at 10:13
  • `BindingFlags.NonPublic | BindingFlags.Static` -- that's looking for a static field, but your `_password` field is an instance field. – canton7 Mar 25 '19 at 10:17

2 Answers2

1

First get the object Type, the get its non public instance fields with the given name. You can then get the value from the object. Example:

public static string ReadPrivateField<T>(T obj, string fieldName)
{
    var type = typeof(T);
    var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
    var value = field.GetValue(obj);
    return value as string;
}
kaffekopp
  • 2,551
  • 6
  • 13
1

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;
}
Rain336
  • 1,450
  • 14
  • 21