Friday, April 4, 2008

Calling Private Methods Externally

I used to think that if I wanted to secure a piece of code, that marking it as "private" would do the trick. Apparently not. By using reflection, you can actually call a private method!

See the code below:


class Program
{
static void Main(string[] args)
{
Type fooType = typeof(Foo);
MethodInfo fightMethod = fooType.GetMethod("Fight", BindingFlags.NonPublic | BindingFlags.Instance);
Foo fightingFoo = new Foo();
fightMethod.Invoke(fightingFoo, new Object[] { "you evil genius!" });
Console.ReadLine();
}
}

public class Foo
{
private void Fight(string value)
{
Console.WriteLine("I will beat you! You're going down, " + value);
}
}