Search code examples
c#stringreflectionmethodinfo

Get MethodInfo of String.Trim with reflection?


I can get MethodInfo of String.Trim as follows, It's OK but gotten method info doesn't have a string parameter! Is it OK?

typeof(string).GetMethod("Trim", new Type[ ] {});

The following code return null, why?:

typeof(string).GetMethod("Trim", BindingFlags.Public);

And how can we use (invoke) Trim method info?


Solution

  • Since in your first example, you specifically ask for a method that has no parameters, you get the overload without any parameters.

    If you want the overload with parameters, you need to say so:

    typeof(string).GetMethod("Trim", new [] { typeof(char[]) });
    

    To invoke an instance method via MethodInfo, you need to pass the instance reference to the Invoke() method:

    // Parameterless overload
    methodInfo.Invoke(myStringInstance, null);
    
    // Single-parameter overload
    methodInfo.Invoke(myStringInstance, new [] { new [] { ' ', '\r', '\n' } });
    

    In your second example, you specified neither BindingFlags.Instance or BindingFlags.Static, so (as documented) the method returned null. Specify one or the other (BindingFlags.Instance for the Trim() method) to get a valid return value (assuming only one method matches...in this case, there is more than one so you'll get an error).