Search code examples
c#reflectioninvokemethodinfo

What is the Object paramter in MethodInfo.Invoke() for?


What is the purpose of the Object obj parameter of MethodInfo.Invoke()?

The MSDN documentation says:

The object on which to invoke the method or constructor

I don't understand how you invoke a method "on" an object. I thought you just called a method from Main() or a class and that's it.

And, am I able to use just any object of any type for this parameter?


Solution

  • If the method is static you do just invoke the method, and in those cases, you pass null to that argument of Invoke.

    For instance methods, you call the method on an instance of the object, not just on "nothing". The object instance that you would normally be calling the method on is what you pass to Invoke.

    As an example, if you had:

    string s = "hi";
    var s2 = s.Trim();
    

    You could model that in reflection by doing:

    string s = "hi";
    MethodInfo trimMethod = GetTrimMethodInfo();
    object s2 = trimMethod.Invoke(s);