C# Language Basic Overloading Example

Download C# Language for free

Example

This code contains an overloaded method named Hello:

class Example
{
    public static void Hello(int arg)
    {
        Console.WriteLine("int");
    }
 
    public static void Hello(double arg)
    {
        Console.WriteLine("double");
    }
 
    public static void Main(string[] args) 
    {
        Hello(0);
        Hello(0.0);
    }
}

When the Main method is called, it will print

int
double

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.

Passing null as one of the arguments