Way to access private members of an object from another object

Posted by Virendradugar under C# category on | Views : 2847
Create a sample class which have private variables. See below Code.

public class Sample
private int i;
internal int j;
protected int k;
private static string str;

In other class, access Private variables via reflection.

class Program
static void Main(string[] args)
Type t= typeof(Sample);
//To access members of any class use MemberInfo class.
MemberInfo[] mem = t.GetMembers();
BindingFlags PB = BindingFlags.NonPublic | BindingFlags.Instance;
//To access field of any class use FieldInfo class.
FieldInfo[] f = t.GetFields(PB);
foreach (FieldInfo m in f)

We need to use BindingFlags to search for the private member.

BindingFlags PB = BindingFlags.NonPublic | BindingFlags.Instance;

This line creates a BindingFlag which tells that search for NonPublic members. We must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

If we use this Binding

BindingFlags PB = BindingFlags.NonPublic | BindingFlags.Instance;

We will not be able to access private static string str; as it is static. BindingFlags.Instance denotes to search for non-static field. We need to use BindingFlags.Static to find out static members.

This will give list of all the private fields (Static or non-static)

BindingFlags PB = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;

Comments or Responses

Login to post response