Re: Overloading and method signatures.

From: Bruce Wood (brucewood_at_canada.com)
Date: 03/05/05


Date: 4 Mar 2005 21:48:45 -0800

The simple answer is because of precisely the example you gave: there
are many situations in which the compiler can't determine which one to
call.

The more complex answer involves looking at the solution you proposed,
and seeing it from the compiler's point of view. You suggested this bit
of code to disambiguate the situation:

class foo {
  int myMethod(string) { ... }
  double myMethod(string) { ... }
}

Decimal Num = 1.0 + (double)myMethod("Dave") + 7;

where the cast to (double) tells the compiler which method to call.
However, compilers don't see things that way.

As soon as you evaluate 'myMethod("Dave")', it becomes a value to be
used in a calculation. The compiler doesn't "look ahead," as such, to
see what kind of value it's going to need in the expression, or to what
kind of value this value is going to be cast. That's all "in the
future" as it were.

This isn't unique to C#, by the way. I know of no language that allows
overloads that will distinguish between two methods based on their
return values alone. In particular, C++ and Java, which provided
inspiration for C#, don't allow it, either.



Relevant Pages

  • Re: problem with memcpy and pointers/arrays confusion - again
    ... this second method is known as an explicit conversion, or cast. ... The cast, in effect, tells the compiler: ... the malloc function. ... function taking a size_t as a parameter and returning a void pointer (i.e. ...
    (comp.lang.c)
  • Re: about the array
    ... 3- If you cast to the wrong type by accident, ... are malloc and free. ... the compiler should issue a diagnostic - gcc ... unknown set of arguments, and return an int. ...
    (comp.lang.c)
  • Re: Can generics really produce strongly typed collections?
    ... The compiler won't detect the bug at compile time. ... will try to cast to B, ... The "foreach" statement specifically behaves in the way you ... interface, assuming one exists. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: a case for multiple inheritance
    ... and overrides the write functions to change ... the compiler would optimize it so that the double function call would be ... private new void Foo ... The cast not much ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: about the array
    ... I guess the bottom line is - if the cast isn't necessary, why do it, esp. ... the compiler should issue a diagnostic - gcc gives: ... it], and screw up, e.g., without the declaration, the compiler *should* ... maybe the int taken by the ...
    (comp.lang.c)