Search code examples
c#.netreflectionprivate-methods

How do I use reflection to invoke a private method?


There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });

In this case, GetMethod() will not return private methods. What BindingFlags do I need to supply to GetMethod() so that it can locate private methods?


Solution

  • Simply change your code to use the overloaded version of GetMethod that accepts BindingFlags:

    MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, 
        BindingFlags.NonPublic | BindingFlags.Instance);
    dynMethod.Invoke(this, new object[] { methodParams });
    

    Here's the BindingFlags enumeration documentation.