Friday, January 18, 2008

Access Private Fields And Invoke Private Methods In .NET

using System;
using System.Reflection;

class Test
{
private int _number;
private int Number
{
get { return _number; }
set { _number = value; }
}

private int PrivateAdd(int a, int b)
{
return a + b;
}

private static int StaticAdd(int a, int b)
{
return a + b;
}

static void Main()
{
//Instance method
Test test = new Test();
MethodInfo privateMethod = test.GetType().GetMethod("PrivateAdd",
BindingFlags.NonPublic | BindingFlags.Instance);
object[] parameters = new object[] { 1, 2 };
int result = (int)privateMethod.Invoke(test, parameters);

//Static method
MethodInfo staticMethod = typeof(Test).GetMethod("StaticAdd",
BindingFlags.NonPublic | BindingFlags.Static);
result = (int)staticMethod.Invoke(null, parameters);

//Private field
FieldInfo privateField = test.GetType().GetField("_number",
BindingFlags.NonPublic | BindingFlags.Instance);
privateField.SetValue(test, 123);
result = (int)privateField.GetValue(test);

//Private property
PropertyInfo privateProperty = test.GetType().GetProperty("Number",
BindingFlags.NonPublic | BindingFlags.Instance);
privateProperty.SetValue(test, 456, null);
result = (int)privateProperty.GetValue(test, null);

Console.WriteLine("Done");
Console.Read();
}
}