Why does C # not consider the return type of a function in polymorphism?

There are two functions with the same name and the same set of parameters, but with different return types. Why is this not a form of polymorphism, that is, method overloading? Why is this not allowed by the compiler?

+7
polymorphism c # oop method-overloading
source share
5 answers

Because C # is designed in such a way that types can be parsed from the inside out. Imagine if you have

int N() {} float N()() {} 

and then call

 float x = N(); 

OK, fine, obviously, we could say that the floating point version was needed. But then you say:

 void M(int x) {} void M(float x) {} M(N()); 

OK, now what version was needed? The rule shows what N () means , and then figure out what is the best overload of M when you know what N () means . You reason from the inside out.

Resolving overloads based on the type of return requires external reasoning inward, and this can be much more complicated.

+14
source share

Consider the following:

 int combine(int a, int b) { return a + b; } float combine(int a, int b) { return a - b; } 

If I had to call the combination (1, 2), the compiler could not find out which of the two methods I want to call (this is ambiguous).

You can almost do an example of checking return types, but what about:

 var c = combine(1, 2); dynamic d = combine(1, 2); combine(1, 2); 

In the above, what should be the value of c or d? 3? -one? This is impossible to say. What about the last statement where no value is assigned? I did not define the overload that void returns, and which of the two methods should it call?

+3
source share

To avoid the ambiguity of the call site. Consider the following interface:

 interface ISomething{ int DoSomething() void DoSomething() } 

now when you call

 myISomething.DoSomething() 

which should be called?

+2
source share

Because it is not necessary to assign the return type to a variable. the compiler cannot force the return value of a variable. even if provided for this, it makes no sense to stop assigning an integer value to a float. as shown in another answer.

0
source share

I believe that this can be realized with the help of a complex set of rules (ensuring unambiguity), but numerous ways of accidentally breaking the code will appear in it.

This would lead to many confusing language quirks because of how inevitably complex rules would be (like similar comparison operators in PHP).

Is it worth it? What do we get from this. The question “why not” should be canceled: why yes?

0
source share

All Articles