user7127000
user7127000

Reputation: 3233

How to use Reflection to call a method of type "private async Task"

I have a class called PageProcessor with a method

private static async Task InsertPosts(IEnumerable<LrcPost> posts)
{
   // ...
}

and I'm trying to call it in one of my unit tests like

PageProcessor processor = new PageProcessor();
MethodInfo dynMethod = processor.GetType()
    .GetMethod
    (
        "InsertPosts",
        BindingFlags.NonPublic | BindingFlags.Instance
    );

dynMethod.Invoke(processor, new object[] { posts });

but am getting an NRE. Any idea why?

Upvotes: 2

Views: 1043

Answers (1)

Nkosi
Nkosi

Reputation: 247068

The method info is null when you try to access it because it is a static member and not an instance member.

Access the method as static member and not an instance member. Also because it is static an instance is not needed to invoke method.

var type = typeof(PageProcessor);
var method = type.GetMethod("InsertPosts", BindingFlags.NonPublic | BindingFlags.Static);
var task = method.Invoke(null, new object[] { posts }) as Task;

Upvotes: 3

Related Questions