How to call a private method in C# – Programming, Pseudocode Example, C# Programming Example

How to call a private method in C#

Recently, I had to look for a solution to be able to recover a value from a private property.

This value was needed to decode an HTTP stream and unfortunately it was encapsulated (and hidden) by the .NET framework.

Fortunately, in .NET, it is very easy to access a private member of another class.

Of course, this type of mechanism breaks the encapsulation and is contrary to the object principles. Nevertheless, sometimes it becomes necessary.

My need was: I wanted to make a call to a private method in another class. By default, the compiler forbids it, this is the reason for the private keyword.

By the reflection mechanisms proposed by .NET, it is possible to reach almost any member of any class.

The operation is performed as follows:

  • First of all, you have to recover the instance of the class you want to “spy on”.
  • Then, we get its type with the GetType() method.
  • From there, we get either a member directly (if we know the name), or by listing members (GetFields, GetMethods). In the example, I know the name.
  • An invocation is then performed to retrieve the value of the member (property or method).

Here’s an example that just shows how it works:

So that’s a simple way to access a private member. Be careful, however, to use this with caution because all private members can change from one version of the framework to another (which may therefore require you to review the “trick” with each new version).

For those who have already used reflection, have you ever used this type of trick to access hidden values in the .NET framework?

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.