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

To call a protected static method on an instance of a class in C#, you can use reflection.

  1. First, get the type of the class using the GetType() method on an instance of the class.
main.cs
MyClass myObj = new MyClass();
Type myType = myObj.GetType();
62 chars
3 lines
  1. Next, use the GetMethod() method to get the method info of the protected static method you want to call.
main.cs
System.Reflection.MethodInfo myMethod = myType.GetMethod("MyProtectedStaticMethod", 
BindingFlags.NonPublic | BindingFlags.Static);
132 chars
3 lines

The first parameter of GetMethod() is the name of the protected static method, and the second parameter is a BindingFlags enumeration value that specifies that the method is not public and is static.

  1. Finally, invoke the method on the instance of the class using the Invoke() method.
main.cs
myMethod.Invoke(null, null);
29 chars
2 lines

Since the method is static, you can pass in null for the first parameter of Invoke(). The second parameter is an array of parameters to pass to the method, but since the protected static method has no parameters, we can pass in null again.

Note: This approach is not recommended as it may violate the intended visibility of the method, and should be used judiciously.

gistlibby LogSnag