Method Overloading with different return type

63,382

Solution 1

The C# specification (section 10.6) states that overloaded members may not differ by only return type and as per http://msdn.microsoft.com/en-us/library/ms229029.aspx

As per your question regarding creating parameters simply to support differing return types? I personally believe that is a terrible solution to the problem. Code maintenance will become difficult and unused parameters are a definite code smell. Does the method really need to be overloaded in that case? Or does it belong in that class? Should something else be created to convert from one return type to another? All things you should ask to derive a more idiomatic solution.

Solution 2

This is logically impossible. Consider the following call:

object o = Bar(42);

or even

var o = Bar(42);

How would the compiler know which method to call?

Edit: Now that I understand what you're actually asking, I think overloading by meaningless parameters is bad practice, and diminished readability, it is much preferable to distinguish by method name:

 string BarToStr()
 {

 }

 int BarToInt()
 {

 }

Solution 3

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:

public T Bar<T>(int a) {
   // code
}

And call it like this:

int i = Bar<int>(42);
string s = Bar<string>(42);

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.

Solution 4

You can not overload the function by differing only their return type. You can only overload the function in the following ways

  1. Parameter types
  2. Number of parameters
  3. Order of the parameters declared in the method

You can not come to know which function is actually called (if it was possible).

One more thing I would like to add is function overloading is providing a function with the same name, but with a different signature. but the return type of a method is not considered as a part of the method's signature.

So this is another way to understand why method overloading can't be done only by return type.

Solution 5

any one having any experience with this, overloading on return type with different parameters should be a bad practice, is it.

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"

Share:
63,382

Related videos on Youtube

Adil Abbasi
Author by

Adil Abbasi

I'm a software engineer and technology enthusiast. Self motivated with countable knowledge of software development techniques, good experience, strong concepts, excellent problem solving idea's and tailored solutions to meet ever-changing business requirements for diverse applications. Like challenges and try to solve each problem completely and perfectly.

Updated on March 03, 2020

Comments

  • Adil Abbasi
    Adil Abbasi about 4 years

    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.

    • Chris Leyva
      Chris Leyva over 10 years
      Can you make your question clearer? I think everyone has misunderstood your question.
    • Rotem
      Rotem over 10 years
      @ChrisLava What other possible meaning is there other than that given in the answers?
    • Chris Leyva
      Chris Leyva over 10 years
      @Rotem he says that he knows why the second code snippet fails ("unable to decide which function to call"). So he understands that. But it seems to me that he is asking if it is bad practice to "overload on return type with different paramaters" (the first code snippet).
    • NDJ
      NDJ over 10 years
      @ChrisLava that's what I took it to be - and answered as such accordingly
    • Rotem
      Rotem over 10 years
      @ChrisLava You're right, I'm not sure how we all missed the point, I read it like 5 times :) I've updated my answer, though now the question seems opinion based.
    • Chris Leyva
      Chris Leyva over 10 years
      @Rotem it's ok. Not your fault. This question could be much clearer. In fact, the whole second code snippet should go away and he should just ask if the first code snippet is bad practice.
    • Adil Abbasi
      Adil Abbasi over 10 years
      I have updated question, I have got a lot of answers about first snippet, hope any one will shear anything about second one.
    • Michael Edenfield
      Michael Edenfield over 10 years
      @AdilAbbasi there are two different questions here. The first is "is my first code snippet a good idea?", which has been answered below. The second is "why can't I overload by return type only" and has been answered before on this site. I'd recommend you take the second part of your question out so this does not appear to be a duplicate.
    • Adil Abbasi
      Adil Abbasi over 10 years
      @MichaelEdenfield I guess the question was still complicated so I have updated it again. Have got satisfying answers but last part of the question is disturbing me. I hope it is clear now.
  • Chris Leyva
    Chris Leyva over 10 years
    Exactly! This is the question as I understand it. Everyone else misunderstood. Not their fault though, because the OP worded this question badly.
  • NDJ
    NDJ over 10 years
    glad its not just me that read it like that!
  • Chris Leyva
    Chris Leyva over 10 years
    To add to your answer, I think it is bad practice and 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.
  • NDJ
    NDJ over 10 years
    agree - have updated answer with your comments
  • Adil Abbasi
    Adil Abbasi over 10 years
    @ChrisLava I got what you are trying to say but I am at structure level at the moment actual functions will be doing something complicated.
  • Eric J.
    Eric J. over 8 years
    The compiler could generate an error, if it is unable to resolve the correct overload. That would allow string foo = BarToStr(). See the closed-as-duplicate answer for more.
  • Aheho
    Aheho over 8 years
    What would the // code section look like? Can you do a switch statement on <T>?
  • Olivier Jacot-Descombes
    Olivier Jacot-Descombes over 8 years
  • Aheho
    Aheho over 8 years
    I assume that wouldn't work with non-native types.
  • Olivier Jacot-Descombes
    Olivier Jacot-Descombes over 8 years
    For other types you must use if-else. But a better approach (if possible) is to define an interface and apply it as a generic type constraint where T : IMyInterface
  • Tim M.
    Tim M. about 6 years
    It's maybe impossible within the current language. It certainly isn't "logically impossible". As Eric J., says, it would be quite easy to choose a method in case where the line is like String foo = Bar(). In cases like Object foo = Bar(), it seems to me that it would be quite easy to have programmers disambiguate with something like Object foo = Bar<String>(). A similar functionality with overloading by type parameter already exists. I don't think there's any practical reason this is impossible or infeasible, it just hasn't been implemented, perhaps for historical reasons.
  • Aisah Hamzah
    Aisah Hamzah over 4 years
    This is partially untrue. The return type is part of the signature. In fact, the CLR allows overloading by return type, as do other languages, like F#. It's just that C# doesn't. Another way to look at it is that without the return type, one cannot uniquely describe the contract that a method or function adheres to.
  • Xonatron
    Xonatron about 2 years
    Also shows the limitations of "var."