In C# I need to be able to define a method but have it return one or two return types. The compiler gives me an error when I try to do it, but why isn't it smart enough to know which method I need to call?
int x = FunctionReturnsIntOrString();
Why would the compiler prevent me from having two functions with different return types?
In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Return type must be same or covariant in method overriding.
In java, method overloading is not possible by changing the return type of the method only because of ambiguity.
No, you cannot overload a method based on different return type but same argument type and number in java. same name. different parameters (different type or, different number or both).
Return type does not matter while overloading a method. We just need to ensure there is no ambiguity! The only way Java can know which method to call is by differentiating the types of the argument list.
From the last paragraph of section 1.6.6 of the C# 3.0 language specification:
The signature of a method must be unique in the class in which the method is declared. The signature of a method consists of the name of the method, the number of type parameters and the number, modifiers, and types of its parameters. The signature of a method does not include the return type.
In IL two methods can differ by return type alone, but outside of reflection there is no means to call a method that differs only be return type.
While it may be obvious in this particular scenario, there are many scenarios where this is in fact not obvious. Lets take the following API for an example
class Bar {
public static int Foo();
public static string Foo();
}
It's simply not possible for the compiler to know which Foo to call in the following scenarios
void Ambiguous() {
Bar.Foo();
object o = Bar.Foo();
Dog d = (Dog)(Bar.Foo());
var x = Bar.Foo();
Console.WriteLine(Bar.Foo());
}
These are just a few quick samples. More contrived and evil problems surely exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With