This question already has an answer here:
- Function overloading by return type? 14 answers
I am want to dig in that whether it is an ambiguity or an extra feature that is provided:
public class Foo
{
public int Bar(){
//code
}
public string Bar(int a){
//code
}
}
Any one having any experience with this, overloading on return type with different parameters should be a bad practice, is it?
But if the overloading was done on the basis of return type then why this is not working for.
public class Foo
{
public int Bar(int a){
//code
}
public string Bar(int a){
//code
}
}
As it will be unable to decide which function to call 1st or second, if we call obj.Bar(); , it should end in error do any one have any idea about it why it allows first code snippet to run.
Check this.. You can't have method with same signature and just different return type. Recommended is mentioned in this question.
C# Overload return type - recommended approach
Others already explained the situation. I only would like to add this: You can do what you have in mind by using a generic type parameter:
And call it like this:
The problem is that it is often difficult to do something meaningful with a generic type, e.g. you cannot apply arithmetic operations to it. Sometimes generic type constraints can help.
I'm taking that to mean - "is it bad practice to use differing parameter combinations to facilitate different return types" - if that is indeed the question, then just imagine someone else coming across this code in a few months time - effectively "dummy" parameters to determine return type...it would be quite hard to understand what's going on.
Edit - as ChrisLava points out "the way around this is to have better names for each function (instead of overloading). Names that have clear meaning within the application. There is no reason why Bar should return an int and a string. I could see just calling ToString() on the int"