Manish Dubey
Manish Dubey

Reputation: 714

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

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

Upvotes: 8

Views: 667

Answers (5)

Acorn1010
Acorn1010

Reputation: 124

Consider the following:

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

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

If I were to call combine(1, 2), there is no way for the compiler to know which of the two methods I want to call (it's ambiguous).

You could almost make a case for checking return types, but what about:

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

In the above, what should the value of c or d be? 3? -1? It's impossible to tell. How about the last statement, where there's no value being assigned? I didn't define an overload that returns void, so which of the two methods should it call?

Upvotes: 3

Konrad Morawski
Konrad Morawski

Reputation: 8394

I believe this could be implemented with a complex set of rules (enforcing unambiguity), but it would introduce numerous ways of accidentally breaking the code.

It would bring along many confusing language quirks due to how inevitably complex the rules would be (kind of like comparison operators in PHP).

Is it worth it? What do we gain by this. The question "why not" should be reversed: why yes?

Upvotes: 0

Eric Lippert
Eric Lippert

Reputation: 660128

Because C# is designed so that types can be analyzed from inside to outside. Imagine if you have

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

and then a call

float x = N();

OK, great, obviously we could say that the float version was wanted. But then you say:

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

M(N());

OK, now which version was wanted? The rule is figure out what N() means and then figure out what the best overload of M is once you know what N() means. You reason from inside to outside.

Overload resolution based on return type requires reasoning from outside to inside and that can be a lot harder.

Upvotes: 16

Tauseef
Tauseef

Reputation: 2052

Because it is not compulsory to assign the return type to a variable. the compiler can not enforce to assign the returned value to a variable. even if it enforces to do so, it makes no sense to stop assigning a integer value to a float. as shown in another answer.

Upvotes: 0

spender
spender

Reputation: 120450

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

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

now when you call

myISomething.DoSomething()

which should be called?

Upvotes: 2

Related Questions