Basic Overloading Example C# with Example



Basic Overloading Example C# with 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 
0
At compile-time, when the compiler finds the method call Hello( ), 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". 
0
Thus, in the case of Hello( ), 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. 

0 Comment's

Comment Form

Submit Comment