0

ok I do have class like this.

Namespace mySpace

 Public Class ClassA

     Private Function MethodA(prm AS Boolean) As Boolean
       Return False
     End Function

     Private Function MethodB() As Boolean
       Return False
     End Function

 End Class

 Public Class ClassB

     Private Function MethodC() As Boolean
       Return True
     End Function

     Private Function InvokeA() As Boolean
        Dim methodObj As MethodInfo
        'null pointer except below here
        methodObj = Type.GetType("mySpace.ClassA").GetMethod("MethodA") 
        Dim params As Boolean() = {False}
        Return CBool(methodObj.Invoke(New ClassA(), params)) 
     End Function

 End Class

End Namespace

What I am trying here is to invoke a method from a different class with parameters using its method. But this returns a null pointer exception. Why? Where I went wrong?

1 Answer 1

1

You are doing various things wrong. The following code should work without any problem:

Dim objA As ClassA = New ClassA()
methodObj = objA.GetType().GetMethod("MethodA", BindingFlags.Instance Or BindingFlags.NonPublic)
Dim params As Object() = {False}
methodObj.Invoke(objA, params)

You have various errors which shouldn't allow your code to run at all, namely:

  • You are retrieving a private method without the adequate BindingFlags.
  • You are not passing the arguments as Object type.

Additionally, you are not using GetMethod with an instantiated object of ClassA (e.g., objA above) and instance.GetType(); I am not 100% sure that you need to do that (perhaps you can accomplish it as you intend), but performing this step is a pretty quick process and would allow the code above to work without any problem.

Sign up to request clarification or add additional context in comments.

12 Comments

-1 for suggesting to create a new instance to get the type of an instance if the type is already well known (why not just GetType(ClassA)?). Also, you're using the wrong BindingFlags, too. It should be BindingFlags.Instance instead of BindingFlags.CreateInstance
@DominicKexel the bindingFlag was a typo. And I haven't suggested to instantiate a new ClassA, I have said that I wasn't sure. Could you please write a code as you suggest?
@DominicKexel instead critising, you should contribute towards solving the problems, don't you think (haven't either see your solution in the other critic you made). I look forward to your solution.
Type.GetType("mySpace.ClassA") works fine, or you could just use GetType(ClassA) to get the Type (as I said in my comment).
@DominicKexel I am trying it and it does not work. Could you please, write a code confim that it works as you suggest, otherwise remove your -1?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.