Proper use of Reflection and binding flags

1.6k Views Asked by At

I want to modify the below code to be able to use a private method

        //use reflection to Load the data
    var method =
                    typeof(MemberDataFactory)
                    .GetMethod("LoadData")
                    .MakeGenericMethod(new [] { data.GetType() })
                    .Invoke(this, null);

Ive tried the following with no luck:

        //use reflection to Load the data
    var method =
                    typeof(MemberDataFactory)
                    .GetMethod("LoadData")
                    .MakeGenericMethod(new [] { data.GetType() })
                    .Invoke(this, BindingFlags.Instance | BindingFlags.NonPublic, null , null, null);

Also what is "var" in terms of this code? Id prefer to specify its type instead of using var.

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

You want to use this overload of Type.GetMethod(), which is where you pass your binding flags. The default .GetMethod(string) only looks for public methods, so it returns null, hence your null reference exception.

Your code should be something more like:

var method =
        typeof(MemberDataFactory)
        .GetMethod("LoadData", BindingFlags.Instance | BindingFlags.NonPublic) // binding flags go here
        ...