Common Type System—Overloading
Overloading
Multiple methods with the same name can exist on a type. When they do, they must differ in some significant way, leading to something called overloading. Methods may be overloaded through distinguished parameters. Differences by return type only are not sufficient to overload a method.
This capability permits you to create methods with similar functionality for differing parameter types, often a convenient feature for your users. It also allows you to implement default values for arguments, for example by providing versions that simply call other overloads with the default values for certain parameters.
For example, consider the overloaded method Bar on the following type:
class Foo { void Bar() { Bar(10); /* “default” value */ } void Bar(int x) { /*...*/ } void Bar(int x, int y) { /*...*/ } void Bar(object o) { /*...*/ } }
Compilers (and/or late-binders for dynamic languages) have the fun job of overload resolution, a process that consists of matching the arguments of a caller with an appropriate overload for the receiving method. This is essentially a search to find the best match given a set of actual arguments. In general, compilers will choose the most specific match. When an ambiguous match, or no match, is found, a compiler error or warning will often result.
For example, given two methods:
void Foo(object o); void Foo(string s);
The following code would bind to Foo(string) because it is more specific:
Foo("Hello, Binding!");
Of course, there are more complex examples that demonstrate the nitty gritty for these rules. But a little experimentation should help to alleviate any doubt or questions about the way in which binding works in your favorite language. The CTS certainly doesn’t mandate any specific set of overload resolution rules, so it is subject to vary from language to language.
|

