Basic Overloading Example

Download c# eBook


This code contains an overloaded method named Hello:

class Example
    public static void Hello(int arg)
    public static void Hello(double arg)
    public static void Main(string[] args) 

When the Main method is called, it will print


At compile-time, when the compiler finds the method call Hello(0), it finds all methods with the name Hello. In this case, it finds two of them. It then tries to determine which of the methods is better. The algorithm for determining which method is better is complex, but it usually boils down to "make as few implicit conversions as possible".

Thus, in the case of Hello(0), no conversion is needed for the method Hello(int) but an implicit numeric conversion is needed for the method Hello(double). Thus, the first method is chosen by the compiler.

In the case of Hello(0.0), there is no way to convert 0.0 to an int implicitly, so the method Hello(int) is not even considered for overload resolution. Only method remains and so it is chosen by the compiler.


Contributors: 2
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook