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

In C#, private static methods are not directly accessible from outside the class. However, it is possible to invoke a private static method on an instance of a class using Reflection.

Here's an example of how to call a private static method on an instance of a class using Reflection:

main.cs
using System;
using System.Reflection;

public class MyClass 
{
    private static void MyPrivateStaticMethod() 
    {
        Console.WriteLine("Hello from MyPrivateStaticMethod!");
    }
}

public static void Main() 
{
    MyClass obj = new MyClass();

    var method = typeof(MyClass).GetMethod("MyPrivateStaticMethod", BindingFlags.NonPublic | BindingFlags.Static);

    method.Invoke(null, null);

    Console.ReadLine();
}
429 chars
22 lines

In this example, we use the GetMethod method from the System.Reflection namespace to retrieve the MyPrivateStaticMethod method of the MyClass class. Since MyPrivateStaticMethod is private and static, we must specify BindingFlags.NonPublic | BindingFlags.Static to access it.

The Invoke method is then used to call the private static method on an instance of the MyClass class. We pass null for the instance parameter, since the method is static and does not require an instance.

Note that calling private static methods in this way is generally discouraged, as it can break encapsulation and lead to unexpected behavior. It should only be used as a last resort.

gistlibby LogSnag