Take a look at setAccessible - a way in Java to let you call private methods by reflections. Why didn't .NET implement such a feature yet?
4 Answers
Here is an example of doing that in .NET
using System;
using System.Reflection;
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
try
{
Console.WriteLine("TestReflect started.");
TestReflect test = new TestReflect();
Console.WriteLine("TestReflect ended.");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
ConsoleKeyInfo cki;
do
{
Console.WriteLine("Press the 'Q' key to exit.");
cki = Console.ReadKey(true);
} while (cki.Key != ConsoleKey.Q);
}
}
public class TestReflect
{
public TestReflect()
{
this.GetType().GetMethod("PublicMethod").Invoke(this, null);
this.GetType().GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);
}
public void PublicMethod()
{
Console.WriteLine("PublicMethod called");
}
private void PrivateMethod()
{
Console.WriteLine("FTW!one1");
}
}

- 90,445
- 31
- 189
- 263
-
The link is broken. Would have been nice if you had copied the useful bits from the site before they took it down, now this accepted answer is not helpful. – NightOwl888 Oct 13 '16 at 14:00
-
1@NightOwl888, fixed it for you. – Yishai Oct 13 '16 at 15:06
You can use reflection to call private methods, though it isn't as straight forward as calling public methods. We've done this before for unit testing and have used the following posts as a how-to reference:
http://www.emadibrahim.com/2008/07/09/unit-test-private-methods-in-visual-studio/
http://johnhann.blogspot.com/2007/04/unit-testing-private-methods.html

- 3,809
- 19
- 22
I think "why" might be a bit of a speculative question, but if you are looking for a way to test private methods, I think you'll be able to do this easier with .NET 4.0:
http://bugsquash.blogspot.com/2009/05/testing-private-methods-with-c-40.html

- 25,181
- 9
- 71
- 121
It's quite possible in .NET to get access to anything private using reflection.
E.g getting acces to a private instance method called Foo on class bar would look like:
typeof(Bar).GetMethod("Foo",BindingFlags.NonPublic | BindingFlags.Instance);
it does however require that the code using reflection is fully trusted.
(The security requirements will be different for V4)

- 21,497
- 7
- 62
- 96