function overloading with different different return type too?

Posted by krrishbiju-15589 under C# on 9/14/2013 | Points: 10 | Views : 5597 | Status : [Member] | Replies : 2
Hello,

Can we achieve function overloading with different different return type too?

public int WrapNumber(int i)
{
return i + 0;
}

public string WrapNumber(int i, int j)
{
return (i + j).ToString();
}

I heard that method overloading is same method name with different signature.
regards
krrish




Responses

Posted by: Allemahesh on: 9/16/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
Dear krrish,

Yes, it is OK to have different return types. The signatures must be different and the signature, explicitly, does not include the return type. C# Language Specification section 3.6

The signature of a method consists of the name of the method, the number of type parameters and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. For these purposes, any type parameter of the method that occurs in the type of a formal parameter is identified not by its name, but by its ordinal position in the type argument list of the method. The signature of a method specifically does not include the return type, the params modifier that may be specified for the right-most parameter, nor the optional type parameter constraints.

So your example is OK because the two methods have different signatures.

However, it is a bad idea to have overloaded methods with different return types. If two methods have different return types then they are doing different actions and should be given different names. The universal expectation is that methods with the same name do a similar operation. Having different return types breaks that expectation and will lead to tears before bedtime.

Happy Coding.

If it helps you or directs U towards the solution, MARK IT AS ANSWER

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 9/18/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Although functions can be distinguished on the basis of return type, they cannot be overloaded on this basis. Const or volatile are only used as a basis for overloading if they are used in a class to apply to the this pointer for the class, not the function's return type. In other words, overloading applies only if the const or volatile keyword follows the function's argument list in the declaration.
we can have different return types too in function overloading....

References:
http://msdn.microsoft.com/en-us/library/5dhe1hce(v=vs.110).aspx
http://csharpindepth.com/Articles/General/Overloading.aspx

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

krrishbiju-15589, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response