newbie_developer
newbie_developer

Reputation: 371

Using Reflection to get static method with its parameters

I'm using a public static class and static method with its parameters:

public static class WLR3Logon
{
   static void getLogon(int accountTypeID)
   {}
}

Now I am trying to fetch the method with its parameters into another class and using the following code:

MethodInfo inf = typeof(WLR3Logon).GetMethod("getLogon",
    BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);

int[] parameters = { accountTypeId };

foreach (int parameter in parameters)
{
    inf.Invoke("getLogon", parameters);
}

But its giving me error

"Object reference not set to an instance of an object."

Where I'm going wrong.

Upvotes: 7

Views: 37700

Answers (4)

newbie_developer
newbie_developer

Reputation: 371

This problem got solved by using the following approach:

using System.Reflection;    
string methodName = "getLogon";
Type type = typeof(WLR3Logon);
MethodInfo info = type.GetMethod(
    methodName, 
    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

object value = info.Invoke(null, new object[] { accountTypeId } );

Upvotes: 19

O. R. Mapper
O. R. Mapper

Reputation: 20731

Your method is private as you have not explicitly declared an access modifier. You have two options to make your code work as intended:

  • Change your method to public.
  • Specify BindingFlags.NonPublic in the GetMethod call

Upvotes: 3

Polity
Polity

Reputation: 15130

There are many problems here

  • Your static method is Private yet you Select a method filtered on publicly visible access only. Either make your method public or ensure that the binding flags include private methods. Right now, no method will be found returning in inf being null which causes your null-ref exception.
  • The parameters is an array of ints where MethodInfo expects an array of objects. You need to ensure that you pass in an array of objects.
  • You loop over the parameters only to invoke the method multiple times with the whole parameter set. Remove the loop.
  • You call MethodInfo.Invoke with the name of the method as the first argument which is useless since this parameter is ment for instances when the method was an instance method. In your case, this argument will be ignored

Upvotes: 7

Talha
Talha

Reputation: 19252

make your method public. It should work after that

 public static class WLR3Logon
 {
       public static void getLogon(int accountTypeID)
       {}
 }

Upvotes: 1

Related Questions