Question

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!

Was it helpful?

Solution

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
        ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top