Thursday, June 28, 2007

Call private function / method using reflection!!!

Dont wonder.Its possible to call a private function is .Net using reflection.

If you run the below program you could see Joy n Code displayed on your screen eventhough that is in a private function called getstr in class pvt.

using System;
using System.Reflection;

namespace ConsoleApplication1 {
class Class1{
STAThread
static void Main(string[] args)
{
pvt b=new pvt();
MethodInfo mi=b.GetType().GetMethod("getstr", BindingFlags.Instance | BindingFlags.NonPublic );
Console.WriteLine ( mi.Invoke(b,null));
Console.ReadLine();
}
}
public class pvt {
private void getstr()
{
Console.WriteLine("Joy n Code");
}
}
}