Blog

Calling Non-Public Methods

January 28, 2010

A typical way for invoking a non-public method of a class is by using reflection. This can come in handy in a number of cases. One typical scenario that comes to mind is when the designers of the .NET Framework or another 3rd party framework decided to bury a class or a method as internal while this could perfectly solve a problem (I just hate it when they do that).

Invoking private methods is not considered a best practice in general, but there are cases where you have no other option than to fall back on using reflection. The following code snippet shows how one would typically accomplish that.

We all recognize this piece of code as we’ve done this at some point in one of our coding sessions. What I want to share here is a slightly nicer way to accomplish the same without all the usual reflection ugliness.

public class Subject
{
    private String DoSomething(String input)
    {
        return input;
    }
}

// Calling code
var subject = new Subject();
var doSomething = typeof(Subject).GetMethod("DoSomething", 
    BindingFlags.Instance | BindingFlags.NonPublic);
var result = doSomething.Invoke(subject, new[] { "Hello Muppets" });
Console.WriteLine(result);  

This code just creates a delegate that matches the signature of the non-public method that we want to call. To me, this approach looks far more elegant. Note that this only works for instance methods and not for static methods.

I hope that this can be of some use.

If you and your team want to learn more about how to write maintainable unit tests and get the most out of TDD practices, make sure to have look at our trainings and workshops or check out the books section. Feel free to reach out at infonull@nullprincipal-itnull.be.

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Author of Writing Maintainable Unit Tests. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Thinking and learning about all kinds of technologies since forever.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be