Wednesday, July 9, 2008

Retrieve a Private Member Variable using Reflection

Despite the private scope modifier, you can still get to a private member variable using Reflection.

Our Example Customer Class:

public class Customer
private int _myPrivateVar = 6;

The code to get the private member variable:

using System.Reflection;

public void test()
Customer myCustomer = new Customer();

object value =
| BindingFlags.NonPublic
| BindingFlags.Instance, null, myCustomer, null);


No comments: