воскресенье, 28 февраля 2010 г.

Getting private fields values using reflection

We can get the private variables values inspite the ones are private. It is not a new idea, just for somebody who does not know

using System.Reflection;
class PrivateFieldsClass
{
    private int myPrivateField = 0;
}

class Program
{
    static void Main(string[] args)
    {
        PrivateFieldsClass myObject = new PrivateFieldsClass();
        FieldInfo fieldInfo = myObject.GetType().GetField("myPrivateField", BindingFlags.Instance BindingFlags.NonPublic);
        fieldInfo.SetValue(myObject, 42);

    }
}
But it works only if you know name of  a variable