I’m back from my marriage and honey moon. So now I’m again having time to do some blogging activities.
Currently, I’m writing a migration procedure from one custom framework (call it framework A) to the other (call it framework B). During the development of the migration procedure I needed the access on the value of a member variable in framework A. Unfortunately, this member variable was private and there was no way to retrieve in another way. Neither, I had the access to the source code of framework A to change the member variable to public. “Damn… how do I get this value?… I need it only once for the migration…”. After a while a simple but effective idea came into my head: Use reflection! In this post I’m going to show a small example on how accessing the private values of an object in C#.
please use reflection carefully. It is a really powerful functionality of C# but is a quite expensive task in execution time.
Walkthrough
In this posing we are creating a simple console application with a class called PrivateClass. The code of this class is shown in the next code snippet.
namespace ReflectionTest
{
public class PrivateClass
{
public PrivateClass()
{
this._privateText = "You can't change me";
this.PrivateNumber = 11;
}
private String _privateText;
private int PrivateNumber { get; set; }
public override string ToString()
{
return String.Format("PrivateNumber: {0}; PrivateText: {1}", this.PrivateNumber, this._privateText);
}
}
}
This example covers the access of a private member variable (line 11) and a private property (line 12). With this class, we are going to show following small demos:
- Demo 1: How do I access the content of the private member variable with reflection?
- Demo 2: How do I modify the content of the private member variable with reflection?
- Demo 3: How do I access the content of the private property with reflection?
- Demo 4: How do I modify the content of the private property with reflection?
Demo 1: How do I access the content of the private member variable with reflection?
An example of how to retrieve a value from a private member variable can be seen in the next code snippet:
static void Main(string[] args)
{
PrivateClass myPrivateClass = new PrivateClass();
// input from ToString() at the beginning to see the content
Console.WriteLine(myPrivateClass);
FieldInfo fi = typeof(PrivateClass).GetField("_privateText", BindingFlags.NonPublic | BindingFlags.Instance);
String valueFromPrivateField = fi.GetValue(myPrivateClass).ToString();
Console.WriteLine("And this was read with reflection: {0}", valueFromPrivateField);
}
In this example, we are first instantiating the class to initialize all desired values and output them in the console output with the overwritten toString method on line 5. The next step is to get the FieldInfo of the desired field in our class. This class contains all necessary information about our field for further processing.
Line 7 searches the field called privateText. With the second parameter we are guaranteeing that we are also getting back a result with a private field. At the end, we can use the “FieldInfo” to retrieve the desired value for any instance that we pass as parameter. The result is then outputted in the console. The results in the console can bee seen in the next figure:
Demo 2: How do I modify the content of the private member variable with reflection?
We saw before that we need the FieldInfo object instance to do something with our private member fields. If you look carefully on the methods that the FieldInfo provides you, you will notice a SetValue method. Guess what it does?
You see the code in the next code snippet:
static void Main(string[] args)
{
PrivateClass myPrivateClass = new PrivateClass();
// input from ToString() at the beginning
Console.WriteLine(myPrivateClass);
FieldInfo fi = typeof(PrivateClass).GetField("_privateText", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(myPrivateClass, "but I'm going to change you!");
Console.WriteLine(myPrivateClass);
}
Most of the code is similar to the previous example. The interesting part lies on line 9 where we are going to change the value of the private member variable to a value that we want. The resulting console output follows:
Demo 3: How do I access the content of the private property with reflection?
Retrieving a private property value is similar to retrieving a member variable value. You only need to change the reflection classes used. I think we don’t need to comment the code anymore, since now it should become self-explanatory. The code snippet and figure for our property example follow (note that I’m writing only the relevant parts of the code):
PropertyInfo pi = typeof(PrivateClass).GetProperty("PrivateNumber", BindingFlags.NonPublic | BindingFlags.Instance);
int value = int.Parse(pi.GetValue(myPrivateClass, new object[0]).ToString());
Console.WriteLine("And the private property value is {0}", value);
and here the resulting console output…
Demo 4: How do I modify the content of the private property with reflection?
Now, modifying a property value should not be any issue for you. In our example we are going to write something like this:
PropertyInfo pi = typeof(PrivateClass).GetProperty("PrivateNumber", BindingFlags.NonPublic | BindingFlags.Instance);
pi.SetValue(myPrivateClass, 20, new object[0]);
Console.WriteLine(myPrivateClass);
and there the console output:
Summary
In this post you saw how to access private fields and properties by using reflection. This is a very powerful functionality of C# and can become very handy in some scenarios (like in my migration procedure
). However, use it carefully when you are working with it. The search of fields and properties can become a quite expensive task in execution time.
Hope this helps,
Patrick


Patrick,<br />Really liked your post. I am having similar requirement, hope you can help me.<br />I am having one user defined control which internally uses another use defined control to store the input value. <br />I can get the members using the below piece of code.<br />MemberInfo [] mf = typeof(CurveIDControl).GetMember(“_textControl”, BindingFlags.NonPublic | BindingFlags.Instance);<br />object obj = mf.GetValue(0); <br /><br />Note: _textControl is of type Framework.View.TextControl<br />Please let me know how can I assign some value to _textControl.<br /><br />Regards, Jiten