Inconsistant null parameter handling in Reflection

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Stefan Hong (stefan_at_mosp.net)
Date: 11/09/04


Date: Tue, 9 Nov 2004 14:09:22 +0800

Hi,

It seems that the way reflection resolves methods is not quite the same as
default CLR. For example this simple class:

  class Test {
    public void Hello(string name) {
      Console.WriteLine("Hello(string)");
    }
    public void Hello(object obj) {
      Console.WriteLine("Hello(object)");
    }
  }

If I invoke the method normally using null parameter:

  Test test = new Test();
  test.Hello(null); // shows Hello(string)

But if I only know the input parameter (which is null) and the name of the
method, and trying to use reflection to resolve the method to invoke, it
becomes:

  Test test = new Test();
  MethodInfo method = test.GetType().GetMethod("Hello", new Type[] {
typeof(void) });
  method.invoke(test, new object[] { null }); // shows Hello(object)

The result changed. It must because of the typeof(void) thing, but I can't
say typeof(string) because the input parameter is null. What should I do to
get the same result?

Thanks,
Stefan



Relevant Pages

  • Re: break out of continuous for loop in key down event?
    ... public void Run ... private void _Thread ... IMHO, this provides a nice concise way to declare simple logic like setting a boolean, but of course you could declare a named method and use that as the event handler in the traditional way. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Problems with Constructor Methods
    ... > public class HelperClass ... > public void readNameAndDisplayItsLength() ... > I guess class test and class NameLength has the same function. ...
    (comp.lang.java.help)
  • Re: How to combine this code in on main class?
    ... then you'll need to instantiate the class ... before calling it. ... > public void printEven ...
    (comp.lang.java.help)
  • a little problem whit java code
    ... QUESTION is how can I print out (class Test). ... public Car(String model, String color, double power){ ... public void setModel ... public void addCar(String model, String color, int power){ ...
    (comp.lang.java.help)