Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading return values [duplicate]

Tags:

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?

like image 835
charlieday Avatar asked Jun 02 '09 04:06

charlieday


People also ask

Should return type be same in method overloading and overriding?

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.

Why method overloading is not possible by changing the return type?

In java, method overloading is not possible by changing the return type of the method only because of ambiguity.

Can the overloaded methods have the same return type?

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).

Does return type matters in method overloading?

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.


2 Answers

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.

like image 172
Timothy Carter Avatar answered Nov 03 '22 08:11

Timothy Carter


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.

like image 24
JaredPar Avatar answered Nov 03 '22 07:11

JaredPar