Glossary / Method overloads

Method overloads

Method overloading defines multiple methods with the same name but different parameter signatures. The compiler selects an overload at compile time using argument count, types, conversions, generic inference, optional parameters, and other resolution rules; overload choice is not generally based on runtime argument type for non-dynamic calls.

Resolution and ambiguity

Overloads can differ by parameter types, count, ref/in/out distinctions, and generic arity under language rules. Return type alone cannot distinguish overloads. Optional arguments and params can make calls ambiguous or cause an overload other than the visually obvious one to be selected. Named arguments improve clarity but are coupled to public parameter names in source usage.

void Log(string message) { }
void Log(Exception error) { }
Log(null); // ambiguous between reference-type overloads

A call with dynamic arguments uses runtime binder overload resolution and can fail later. Overload additions may be source-breaking if they make previously valid calls ambiguous or change resolution. Binary compatibility and source compatibility are different concerns.

API guidance

Keep overload sets small and predictable. Prefer distinct names when semantics differ substantially or null/optional ambiguity is likely. Avoid overloads distinguished only by obscure conversions. Compile representative consumer calls when evolving public APIs.

Interview questions

  1. Can overloads differ only by return type? No.
  2. When is overload resolution performed? Compile time for ordinary calls; dynamic calls bind at runtime.
  3. Why is Log(null) ambiguous? Null converts to multiple unrelated reference types.
  4. Can adding an overload break source code? Yes, it can create ambiguity or alter selected overload.
  5. How reduce ambiguity? Distinct names, clearer parameter shapes, or explicit argument typing.

References