call a private method on an instance of a class in csharp

In C#, private methods can only be accessed within the same class they were defined in. However, there are some scenarios where you may need to call a private method on an instance of that class. One way to do this is by using reflection.

Here's an example code snippet that shows how to invoke a private method on an instance of a class using reflection:

main.cs
using System;
using System.Reflection;

public class MyClass {
   private void MyPrivateMethod(string message){
       Console.WriteLine(message);
   }
}

public class Program {
    static void Main(string[] args) {
        MyClass myClass = new MyClass();
        MethodInfo methodInfo = typeof(MyClass).GetMethod("MyPrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
        methodInfo.Invoke(myClass, new object[] { "Hello, world!" });
    }
}
461 chars
17 lines

In this example, we first create an instance of MyClass. Then, we use reflection to obtain a MethodInfo object for the private method MyPrivateMethod. We specify the BindingFlags.NonPublic flag to indicate that we want to retrieve a private method, and the BindingFlags.Instance flag to indicate that we want to retrieve an instance method.

Finally, we invoke the private method using the methodInfo.Invoke() method, passing in the instance of MyClass and the arguments to the method as an object array. The private method is executed, and the output is displayed on the console.

gistlibby LogSnag