Using C# Reflection to Succinctly Access Private Members

Author by Dalton Smith

Occasionally, when writing C# unit tests, you will come across classes with private members that need to be accessed or modified to properly test the system. In these cases, reflection can be used to gain access to private members of a class. While this breaks encapsulation principles, it is generally acceptable to use for testing purposes.

 

Accessing Private Properties

Accessing private properties is useful in testing for verifying the internal state of a system after performing certain actions. Sometimes, it may also be necessary to set a property's value when it is inaccessible. The following code snippet shows how to modify and access a private property.

 

 

Invoking Private Methods

Sometimes, for complex systems, it may be necessary to validate the operation of private helper methods inside a class. Private methods can be invoked using the syntax shown in the following code snippet.

 

 

GetMethod takes two parameters, the method name and the BindingFlags to use. BindingFlags.NonPublic includes private members in the search, while BindingFlags.Instance includes instance members.