Why can’t two methods be declared with the same signature even though their return types are different? [duplicate]

It’s because of type coercion.

Say you have the following functions:

int x(double);
float x(double);

double y = x(1.0);

Now, which of the two prototypes should you call, especially if they do two totally different things?

Basically, a decision was made early on in the language design to only use the function name and arguments to decide which actual function gets called, and we’re stuck with that until a new standard arrives.

Now, you’ve tagged your question C# but I see nothing wrong with designing a language that can do what you suggest. One possibility would be to flag as an error any ambiguous commands like above and force the user to specify which should be called, such as with casting:

int x(double);
float x(double);
double y = (float)(x(1.0));    // overload casting
double y = float:x(1.0);       // or use new syntax (looks nicer, IMNSHO)

This could allow the compiler to choose the right version. This would even work for some issues that other answers have raised. You could turn the ambiguous:

System.out.Println(myClass.MyMethod());

into the specific:

System.out.Println(string:myClass.MyMethod());

This may be possible to get added to C# if it’s not too far into a standards process (and Microsoft will listen) but I don’t think much of your chances getting it added to C or C++ without an awfully large amount of effort. Maybe doing it as an extension to gcc would be easier.

Leave a Comment