c# – Why is the overloaded method called?

Question:

static void Main(string[] args)
{
     object s = A(null);
}

static object A(object s) { return s; }

static object A(string s) { return s; }

The question is as follows:

  1. Why is a method called with a string input parameter?
  2. Why is the method not called with the input parameter object?

Where can I find information on this?

Answer:

First, the compiler looks at which methods can be called at all. Let's say you have three overloads:

static object A(object s) { return s; }

static object A(string s) { return s; }

static object A(int s) { return s; }

When calling A(null) compiler will only consider the first two overloads, because null not a valid value for int . And when you call A(42) compiler will only consider the first and third overloads, because 42 not a valid value for string .

Second, the compiler will choose the one with the most specific type from among the appropriate methods. In this case, it's string . The compiler is guided by the same principle "closer is better", for example, when choosing methods between the current and the parent class.

Details can be found in the specification. There are also short articles on overloading from Jon Skeet and Eric Lippert .

Scroll to Top