Access private members of a class using reflection

 
 
  • Gérald Barré

Accessing private members of a class is generally not a good thing. However, sometimes this is required. Here are some methods to facilitate access to private members:

C#
public static T GetPrivateField<T>(this object obj, string name)
{
    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    Type type = obj.GetType();
    FieldInfo field = type.GetField(name, flags);
    return (T)field.GetValue(obj);
}

public static T GetPrivateProperty<T>(this object obj, string name)
{
    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    Type type = obj.GetType();
    PropertyInfo field = type.GetProperty(name, flags);
    return (T)field.GetValue(obj, null);
}

public static void SetPrivateField(this object obj, string name, object value)
{
    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    Type type = obj.GetType();
    FieldInfo field = type.GetField(name, flags);
    field.SetValue(obj, value);
}

public static void SetPrivateProperty(this object obj, string name, object value)
{
    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    Type type = obj.GetType();
    PropertyInfo field = type.GetProperty(name, flags);
    field.SetValue(obj, value, null);
}

public static T CallPrivateMethod<T>(this object obj, string name, params object[] param)
{
    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    Type type = obj.GetType();
    MethodInfo method = type.GetMethod(name, flags);
    return (T)method.Invoke(obj, param);
}

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub