Get MethodInfo of String.Trim with reflection?

952 Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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).

0
On

When you do typeof(string).GetMethod("Trim", new Type[ ] {});, you are asking to retrieve the overload of the method which does not take any parameters. That is why there is no parameter shown in the output. If instead you do this typeof(string).GetMethod("Trim", new Type[ ] {typeof(char[])});, it will return the corresponding overload.

Regarding the second issue, you can overcome this problem by setting the flag for indicating instance method i.e. BindingFlags.Public|BindingFlags.Instance. This will however, merely change the error to an ambiguous match issue. I would suggest you pass in the parameter type list as well to overcome that.