I never knew: C# method overloads can return different types


I came to C# from Java, which I’m pretty sure doesn’t (or maybe didn’t) allow this, so I was super surprised today when I learnt that C# method overloads can have different return types.


So this class is completely valid:


public class Foo
{
    public Foo Bar();
    public string Bar(Foo foo);
}


For years I’ve thought all overloads had to return the same type, so I’ve designed around a non-existent limitation !


So I’m wondering if any of the APIs I’ve designed over the years would have been ‘better’ if I’d realized this sooner?


What do you think? Is it a good idea to do this?

Comments (4)

  1. Keith Farmer says:

    Consider:

    class Math

    {

       int Add(int, int)

       double Add(double, double)

    }

    .. Now ask yourself again — is this a good idea?

    Of course it is, provided the API itself makes sense (which is a general requirement of good API, anyway).  If you swapped return types, such that Add(double, double) returned int, and vice versa, it’d be a horrible API regardless.

    The rule is that overloads may not differ only in return type.  You couldn’t have Add(int, int) return int and Add(int, int) return double in the same class.

  2. decarufe says:

    I was about to answer that this is usually a bad idea, and it is, but I agree on the Math class sample.

    In most other cases, though, you want the return type to be exactly what you expect. It will be hard to read your code if you return many different unrelated types from many different overloads.

    In the case of the Add method, it can be generic, like:

    T Add<T>(T first, T second)

  3. Anonymous says:

    The rule is that overloads may not differ only in return type

    Actually IL allows this just none of the MS core languages (other than maybe Managed C++ but don’t quote me) support it as a concept.

  4. Anonymous says:

    Yes, in fact, Java allows overloads to have different return types. It follows the same rule as C# (and C++ before it), which kfarmer quoted:

    The rule is that overloads may not differ only in return type