C# – How to call a static method using reflection

You can use reflection to get properties or methods programmatically at runtime. Here’s an example of calling a static method with reflection:

MethodInfo builderMethod = typeof(Type).GetMethod(StaticMethodName, BindingFlags.Static | BindingFlags.Public);

var request = (ReturnType)builderMethod.Invoke(null, null);
Code language: C# (cs)

Note: This static method is parameterless. If you have parameters, you have to pass them in like this .Invoke(null, param1, param2).

Example – passing static method names to a parameterized unit test

With parameterized tests you can only pass in compile-time constants. This means you can’t pass object instances or delegates (Action/Func/Lambda).

I have a class called RequestProcessor that processes IRequest objects. I want to verify it can successfully process the different types of requests built using RequestBuilder. And I want to use a parameterized test so I don’t have to duplicate test code.

I can’t pass in the request objects or delegates pointing to the builder methods. Instead, I can pass in the method names, then use reflection to look them up and execute them.

[DataRow(nameof(RequestBuilder.BuildAuthRequest))]
[DataRow(nameof(RequestBuilder.BuildRefundRequest))]
[DataRow(nameof(RequestBuilder.BuildVoidRequest))]
[TestMethod()]
public void TestProcessRequest_WhenValidRequest_ReturnsTrue(string builderMethodName)
{
	//arrange
	var requestProcessor = new RequestProcessor();

	MethodInfo builderMethod = typeof(RequestBuilder).GetMethod(builderMethodName, 
		BindingFlags.Static | BindingFlags.Public);

	IRequest request = (IRequest)builderMethod.Invoke(null, null);

	//act
	var actual = requestProcessor.Process(request);

	//assert
	Assert.IsTrue(actual);
}
Code language: C# (cs)